class Solution {
public:
bool checkInclusion(string s1, string s2) {
int l1=s1.size();
int l2=s2.size();
if(l2<l1)
{
return 0;
}
vector<int>a(123,0);
for(int i=0;i<l1;i++)
{
a[s1[i]]++;
}
int x=0;
int y=l1;
while(y<l2+1)
{
int i=x;
vector<int>b=a;
for( i;i<y;i++)
{
if(b[s2[i]])
{
b[s2[i]]--;
}
else
{
break;
}
}
if(i==y)
{
return 1;
}
x++;
y++;
}
return 0;
}
};
开始还为十分钟一道中等题开心,
看到这结果好像也没多值得开心的。
改一改。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int l1=s1.size();
int l2=s2.size();
if(l2<l1)
{
return 0;
}
int x=0;
int y=l1;
sort(s1.begin(),s1.end());
while(y<l2+1)
{
string s3(s2.begin()+x,s2.begin()+y);
sort(s3.begin(),s3.end());
if(s1==s3)
{
return 1;
}
x++;
y++;
}
return 0;
}
};
笑死,这波反向修改?
参考答案去了。
嗐,加油。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n = s1.length(), m = s2.length();
if (n > m) {
return false;
}
vector<int> cnt1(26), cnt2(26);
for (int i = 0; i < n; ++i) {
++cnt1[s1[i] - 'a'];
++cnt2[s2[i] - 'a'];
}
if (cnt1 == cnt2) {
return true;
}
for (int i = n; i < m; ++i) {
++cnt2[s2[i] - 'a'];
--cnt2[s2[i - n] - 'a'];
if (cnt1 == cnt2) {
return true;
}
}
return false;
}
};
答案有一样的思路,
但是效率却高了很多,
这就体现了代码能力了吧。
加油。
另一个双指针的答案也挺好的。