题目
假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,比如:abcda和adabc,由于出现的字符个数都是相同,只是顺序不同,所以这两个字符串是匹配的。要求高效。
思路
假定字符串中都是ASCII字符。用一个数组来计数,前者加,后者减,全部为0则匹配。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
   | 
 
 
 
 
 
  #include <iostream> #include <cstring> using namespace std;
  class Solution { public:     bool StrMatch(string str1,string str2){         int size1 = str1.size();         int size2 = str2.size();         if(size1 <= 0 || size2 <= 0 || size1 != size2){             return false;         }         int count[256];                  memset(count,0,sizeof(count));                  for(int i = 0; i < size1; ++i){             ++count[str1[i]];         }                  for(int i = 0; i < size2; ++i){             --count[str2[i]];         }                  for(int i = 0; i < 256; ++i){             if(count[i] != 0){                 return false;             }         }         return true;     } };
 
  int main() {     Solution solution;     string str1("afafafa");     string str2("afafaf");     cout<<solution.StrMatch(str1,str2)<<endl; }
 
  |