[leetcode] 791. Custom Sort String

网友投稿 930 2022-08-23

[leetcode] 791. Custom Sort string

[leetcode] 791. Custom Sort String

Description

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

Example :Input: S = "cba"T = "abcd"Output: "cbad"Explanation: "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

Note:

S has length at most 26, and no character is repeated in S.T has length at most 200.S and T consist of lowercase letters only.

分析

题目的意思是:字符串T按照字符串S的单词顺序排序。

原来就用一个hashmap先统计T的词频,然后按照S的顺序输出,最后把hashmap剩下的字符*词频加到res的尾部。string( size_type length, char ch ); 以length为长度的ch的拷贝(即length个ch)

代码

class Solution {public: string customSortString(string S, string T) { string res=""; unordered_map m; for(auto a:T){ m[a]++; } for(char a:S){ res+=string(m[a],a); m[a]=0; } for(auto a:m){ res+=string(a.second,a.first); } return res; }};

参考文献

​​[LeetCode] Custom Sort String 自定义排序的字符串​​​​标准C++中的string类的用法总结(转)​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1276. Number of Burgers with No Waste of Ingredients
下一篇:C语言编程时常犯的18种错误(c语言编程常见错误例题)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~