这道题只关心 orderorderorder 出现的字符,在 sss 中的排序。 sss 中不在 orderorderorder 的字符,在排序后是什么位置,不影响答案。
可以用 sortsortsort 函数,传入我们自定义的排序方式,按照 orderorderorder 中字母顺序排序。
更贴切的,可以用计数排序,统计 sss 中每个字母出现次数 timestimestimes。按照 orderorderorder 的循序,和 timestimestimes 的次数,依次将每个字母加入 ansansans , 最后将剩余字符加入 ansansans,即为所求。
class Solution {
public:string customSortString(string order, string s) {//自定义字符串排序vector cmp(26);for(int i = 0 ;icmp[order[i]-'a'] = i+1;//每个字母的顺序}sort(s.begin(),s.end(),[&](char c0,char c1){//匿名表达式return cmp[c0-'a'] < cmp[c1-'a'];//自定义顺序});return s;}
};
class Solution {
public:string customSortString(string order, string s) {//计数排序vector times(26);for(auto x:s){//记录s中每个字母出现的次数times[x-'a'] ++;//每个字母的顺序}string ans;for(auto x:order){while(times[x-'a']>0){//ans+=string(times[x-'a'],x);ans+=x;times[x-'a']--;//time[x-'a'] = 0;}}for(int i = 0;i<26;i++){//剩余顺序无所谓,关键在于排序orderans+=string(times[i],i+'a');times[i] = 0;}// for(auto x:s){// ans+=string(times[x-'a'],x);// times[x-'a'] = 0;// }return ans;}
};
理解思路很重要!
欢迎读者在评论区留言,作为日更博主,看到就会回复的。
