【C++】:用sort对string类型进行排序

前言

这个问题来自于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 
#include 
#include 
using namespace std;
int main(){
    string s;
    cin>>s;
    cout<cout<return 0;
}

截图:
【C++】:用sort对string类型进行排序_第1张图片
通过这个我们可以看出,sort已经实现了对字符串的排序修改

leetcode代码之一

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        return s==t;
    }
};

超级简单,当然还有一种也很巧的方法,叫做哈希计数,这里暂且不提,放在下一篇博文重点讨论~

你可能感兴趣的:(leecode,C++)