解题方法:
- 用哈希表
unordered_map<char, int>
,记录s1
中字符出现数,并于s2
做对比
- 用
int count[256]
的数组来完成上述工作(桶计数)
- 没想到的方法:将
s1
和s2
内部按照字符升序排序,最后判定两者是否相等即可
2的时间复杂度为\(O(N)\),因为\(N <= 100\),因此可以理解为\(O(1)\)
解法一:
用到了C++ std中的unordered_map
类,需要注意是否可以修改pair
中的值!
it
的类型是什么!!??
unordered_map<char, int>
中,添加新hash对时,初值为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
| class Solution { public: bool CheckPermutation(string s1, string s2) { if(s1.size() != s2.size()) { return false; } unordered_map<char, int> map; for(int i=0; i<s1.size(); ++i) { map[s1[i]] += 1; map[s2[i]] -= 1; } for(auto it : map) { if(it.second != 0) { return false; } } return true; } };
|
解法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public: bool CheckPermutation(string s1, string s2) { if(s1.size() != s2.size()) { return false; } int count[256]; memset(count, 0, sizeof(count)); for(int i=0; i<s1.size(); ++i) { count[int(s1[i])]++; count[int(s2[i])]--; } for(int i=0; i<256; ++i) { if(count[i] != 0) { return false; } } return true; } };
|
解法三
1 2 3 4 5 6 7 8
| class Solution { public: bool CheckPermutation(string s1, string s2) { sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); return s1 == s2; } };
|