Formatted question description: https://leetcode.ca/all/791.html

791. Custom Sort String (Medium)

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.

Companies:
Facebook

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/custom-sort-string/

// Time: O(TlogT)
// Space: O(1)
class Solution {
public:
    string customSortString(string S, string T) {
        int m[26] = { 0 };
        for (int i = 0; i < S.size(); ++i) m[S[i] - 'a'] = i;
        sort(T.begin(), T.end(), [&](const char a, const char b) {
            return m[a - 'a'] < m[b - 'a'];
        });
        return T;
    }
};

Java

class Solution {
    public String customSortString(String S, String T) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int sLength = S.length(), tLength = T.length();
        for (int i = 0; i < sLength; i++)
            map.put(S.charAt(i), i);
        char[] tArray = T.toCharArray();
        Character[] sortedArray = new Character[tLength];
        for (int i = 0; i < tLength; i++)
            sortedArray[i] = tArray[i];
        Arrays.sort(sortedArray, new Comparator<Character>() {
            public int compare(Character c1, Character c2) {
                int order1 = map.getOrDefault(c1, 100);
                int order2 = map.getOrDefault(c2, 100);
                return order1 - order2;
            }
        });
        for (int i = 0; i < tLength; i++)
            tArray[i] = sortedArray[i];
        return new String(tArray);
    }
}

All Problems

All Solutions