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 most26
, and no character is repeated inS
.T
has length at most200
.S
andT
consist of lowercase letters only.
题目:字符串S
和T
只包含小写字符。在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冲突。