【题目】
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
来源:leetcode
链接:https://leetcode-cn.com/problems/check-permutation-lcci/
【示例1】
输入: s1 = “abc”, s2 = “bca”
输出: true
【示例2】
输入: s1 = “abc”, s2 = “bad”
输出: false
【代码】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :6.3 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
map<char,int> m;
bool CheckPermutation(string s1, string s2) {
for(auto x:s1)
m[x]++;
for(auto x:s2){
m[x]--;
if(m[x]<0)
return false;
}
return true;
}
};
【sort函数】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :6.1 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
return s1==s2;
}
};