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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值