leetcode_判断字符串是否为字符重排
今天刷的是offer题:判断两个字符串是否为字符重排
由于时间原因,我最先想到的是遍历第一个字符串,然后从第二个字符串中每次删除第一个字符串中遍历的字符,如果最后剩下的是空串则返回true,否则返回false。
代码如下:
1 class Solution { 2 public: 3 bool CheckPermutation(string s1, string s2) { 4 int size1=s1.size(); 5 int size2=s2.size(); 6 if(size1==0&&size2==0) 7 { 8 return true; 9 } 10 else if(size1!=size2) 11 { 12 return false; 13 } 14 else 15 { 16 for(int i=0;i<size1;i++) 17 { 18 int pos = s2.find_first_of(s1[i]); 19 20 if(pos!=-1) 21 { 22 s2.erase(pos,1); 23 } 24 else 25 { 26 return false; 27 } 28 29 } 30 } 31 return true; 32 33 } 34 };
提交后正确通过,但是时间复杂度太高。

于是想到可以把两个字符串只遍历一遍,然后统计每个字符出现的次数这种方法。
代码如下:
1 class Solution { 2 public: 3 bool CheckPermutation(string s1, string s2) { 4 5 int size1=s1.size(); 6 int size2=s2.size(); 7 if(size1==0&&size2==0) 8 { 9 return true; 10 } 11 else if(size1!=size2) 12 { 13 return false; 14 } 15 else 16 { 17 int temp[26]={0};//用来存储每个字符的出现次数 18 //遍历字符串1,统计每个字符出现的次数 19 for(int i=0;i<size1;i++) 20 { 21 int pos=s1[i]-'a'; 22 temp[pos]++; 23 } 24 //遍历字符串2,每次在数组中对应元素减1 25 for(int i=0;i<size2;i++) 26 { 27 int pos=s2[i]-'a'; 28 temp[pos]--; 29 if(temp[pos]<0) 30 { 31 return false; 32 } 33 } 34 } 35 return true; 36 37 } 38 };
结果时间复杂度只有n,提交结果如下:

浙公网安备 33010602011771号