문제
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.
풀이
딱 위 그림처럼 풀면 된다.
S에 나온 알파벳의 순서대로 T를 정렬하면 되는데
순서를 유지한다는 말을 곰곰히 생각해봤고, S에 나온 각알파벳에 우선순위를 부여하면 풀 수 있지 않을까? 라는 생각이 들었다.
근데 S에 나오지 않은 문자가 T에 나올수 있으니까 그런 문자들은 우선순위를 제일 낮은 0으로 두게끔 풀었다.
그리고 S에 나온 문자들이 T에서 여러번 나올 수가있으니까 T의 모든 문자에 대해서 S에서 정한 우선순위를 적용해야 한다는 생각이 들었다.
그림을 잘 살펴보면 무슨말인지 이해가 갈것이다.
/**
* @param {string} S
* @param {string} T
* @return {string}
*/
var customSortString = function(S, T) {
const sMap = new Map();
for (let i = 0; i < S.length; i++) {
if (!sMap.has(S[i])) sMap.set(S[i], S.length - i);
}
const tArr = [];
for (let i = 0; i < T.length; i++) {
const temp = [T[i], sMap.has(T[i]) ? sMap.get(T[i]) : 0];
tArr.push(temp);
}
tArr.sort((a, b) => b[1] - a[1]);
let result = "";
tArr.forEach((item, index) => {
result += item[0];
});
return result;
};