1.3 Given two strings, write a method to decide if one is a permutation of the other.
Solution 1:
bool isPermutation(string a, string b) {
if (a.length() != b.length())
return false;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a == b;
}
Solution 2:
bool isPermutation(string a, string b) {
if (a.length() != b.length())
return false;
vector<int> c(256, 0);
for (int i = 0; i < a.length(); i++)
c[a[i]]++;
for (int i = 0; i < b.length(); i++) {
c[b[i]]--;
if (c[b[i]] < 0)
return false;
}
return true;
}
本文提供两种方法来判断两个字符串是否互为排列:一种是通过排序比较,另一种是使用计数法。
148

被折叠的 条评论
为什么被折叠?



