0%

面试金典0102 判断是否互为字符重排

题目:判定是否互为字符重排

解题方法:

  1. 用哈希表unordered_map<char, int>,记录s1中字符出现数,并于s2做对比
  2. int count[256]的数组来完成上述工作(桶计数)
  3. 没想到的方法:将s1s2内部按照字符升序排序,最后判定两者是否相等即可

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; // 初值是0吗?
map[s2[i]] -= 1;
}
// unordered_map<char, int>::iterator it;
for(auto it : map) // 这里it的类型是?
{
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;
}
};
欲戴皇冠,必承其重,加油!