【题目】
给定两个字符串 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;
}
};

本文介绍了一种用于检查两个字符串是否可以通过重新排列字符变成彼此的算法。通过使用C++中的map来跟踪字符频率,或者利用sort函数对字符串进行排序并比较,可以高效地解决这个问题。
380

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



