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值.

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