力扣(LeetCode)791. 自定义字符串排序

力扣(LeetCode)791. 自定义字符串排序_第1张图片
思路:
①先对T进行遍历,记录下T中的元素及个数
②然后对S进行遍历,S即为题中定义的字母排序,那么凡是cMap[c] >=1 的,皆为在S和T中同时出现的,那么就留下这些元素,这个顺序刚好就是S的顺序,记得要把cMap[c]的值减掉
③因为全是小写字母,所以可以对ASCII码97-122的字符进行遍历,如果这个字符的cMap[c]>=1就说明是存在于T中,却不在S中的,那么这些就额外添加到result中
④最后返回result

#include
#include
#include
using namespace std;

class Solution
{
public:
    string customSortString(string S, string T)
    {
        string result = "";
        map cMap;
        for(auto c:T)
            cMap[c]++;

        for(auto c:S)
            while(cMap[c]>=1)
            {
                result+=c;
                cMap[c]--;
            }

        for(char c=97; c<=122; c++)
        {
            while(cMap[c]>=1)
            {
                result+=c;
                cMap[c]--;
            }
        }
        return result;
    }
};

int main()
{
    Solution s;
    string S = "kqep";
    string T = "pekeq";
    string result = "";

    result = s.customSortString(S,T);
    cout<

你可能感兴趣的:(LeetCode)