LeetCode791. 自定义字符串排序

791. Custom Sort String

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.

题目:字符串ST只包含小写字符。在S中,所有字符只会出现一次。S已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果S中x在y之前出现,那么返回的字符串中x也应出现在y之前。返回任意一种符合条件的字符串T

思路:参考解析Sort。以S中元素出现的先后顺序作为排序的依据,因此对S中的字符创建map数组,map的value为字符的下标位置。同1122. Relative Sort Array

工程代码下载

class Solution {
public:
    string customSortString(string S, string T) {
        unordered_map<char, int> mp;
        for(int i = 0; i < S.size(); ++i)
            mp[S[i]] = i+1;

        sort(T.begin(), T.end(), [&](char a, char b){return mp[a] < mp[b];});
        
        return T;
    }
};

【注意】

使用lambda表达式时,对map/unordered_map需要使用引用,进行值捕获时会编译出错。

sort(T.begin(), T.end(), [mp](char a, char b){return mp[a] < mp[b];});
solution.cpp: In lambda function:
Line 9: Char 66: error: passing 'const std::unordered_map<char, int>' as 'this' argument discards qualifiers [-fpermissive]
         sort(T.begin(), T.end(), [mp](char a, char b){return mp[a] < mp[b];});

因为当捕获为map/unordered_map的值时,lambda表达式会默认转换为const map/const unordered_map,而mp[a]的操作是若a在mp中不存在,则默认插入,与const冲突。

参考:C++11 lambda表达式不能捕获map/unordered_map值.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章