Given two strings,write a method to decide if one is a permutation of the other.
Example 1
Input: s1 = "abc", s2 = "bca"
Output: true
Example 2
Input: s1 = "abc", s2 = "bad"
Output: false
Note
- 0 <= len(s1) <= 100
- 0 <= len(s2) <= 100
Solution
字符串 s1 和 s2 互为字符重排等价于「两个字符串排序后相等」。因此我们可以对字符串 s1 和 s2 分别排序,看排序后的字符串是否相等即可判断。此外,如果 s1 和 s2 的长度不同,s2 必然不是 s1 的异位词。
int cmp(const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
bool CheckPermutation(char* s1, char* s2){
if (strlen(s1) != strlen(s2)) return false;
qsort(s1, strlen(s1), sizeof(char), cmp);
qsort(s2, strlen(s2), sizeof(char), cmp);
if (strcmp(s1, s2) == 0) return true;
else return false;
}
从另一个角度考虑,字符串 s1 和 s2 互为字符重排等价于「两个字符串中字符出现的种类和次数均相等」。由于字符串只包含 26 个小写字母,因此我们可以维护一个长度为 26 的频次数组,先遍历记录字符串 s1 中字符出现的频次,然后遍历字符串 s2 ,减去对应的频次,如果出现<0,则说明 s2 包含一个不在 s1 中的额外字符,返回 false 即可。但是如果不是 26 个字母就需要建表。
bool CheckPermutation(char* s1, char* s2){
int i, freq[26] = {0};
if (strlen(s1) != strlen(s2)) return false;
i = 0;
while (s1[i]) {
freq[s1[i] - 'a']++;
freq[s2[i] - 'a']--;
i++;
}
for (i = 0; i < 26; i++) {
if (freq[i] != 0) return false;
}
return true;
}