前言
这个问题来自于leetcode上面的一道题
Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
判断两个字符串排序后是否相等
这个方法的妙用就在于省去了自己写排序的时间
具体demo使用
利用sort(s.begin(),s.end()); //这样就可以把字符串给排序了
demo程序如下:
#include <iostream>#include <string>#include <algorithm>using namespace std;int main(){ string s; cin>>s; cout<<s<<endl; sort(s.begin(),s.end()); cout<<s<<endl; return 0;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
截图:
通过这个我们可以看出,sort已经实现了对字符串的排序修改
leetcode代码之一
class Solution {public: bool isAnagram(string s, string t) { sort(s.begin(),s.end()); sort(t.begin(),t.end()); return s==t; }};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
超级简单,当然还有一种也很巧的方法,叫做哈希计数,这里暂且不提,放在下一篇博文重点讨论~