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衝突。