
orderandstrare strings composed of lowercase letters. Inorder, no letter occurs more than once.
orderwas sorted in some custom order previously. We want to permute the characters ofstrso that they match the order thatorderwas sorted. More specifically, ifxoccurs beforeyin order, thenxshould occur beforeyin the returned string.Return any permutation of
str(as a string) that satisfies this property.Example:
Input: order = "cba" str = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.Note:
orderhas length at most26, and no character is repeated inorder.strhas length at most200.orderandstrconsist of lowercase letters only.
class Solution: def customSortString(self, order: str, str: str) -> str: alpha_dict = {} res = "" for i in range(len(order)): alpha_dict[order[i]] = i+1 for i in range(len(str)): if str[i] not in alpha_dict: res += str[i] for i in range(len(order)): for j in range(len(str)): if str[j] in alpha_dict: if alpha_dict[str[j]]==i+1: res += str[j] return res
order : 주어진 순서대로 우선 순위가 정해진다. 우리가 아는 알파벳 순서인 'abcde...z'가 아닌 order에 적혀있는 순서대로 알파벳이 우선순위를 가진다. order = 'dcba'이면 커스텀된 알파벳 순서가 'dcba'가 된다는 뜻이다.
str : 위의 order를 기준으로 순서를 재정렬할 문자열이다. order의 알파벳 순서를 유지하면서 다시 정렬해야 한다. order에 나와있지 않은 알파벳은 아무 위치에 들어가도 된다.
order의 순서를 가지고 str을 재배치 하는 문제이다.
예를 들어,
order = 'cba'
str = 'abcd'
결과 : 'cbad', 'cbda', 'cdba', 'dcba' 네개 중 아무거나 결과가 나오면 된다.
알파벳의 순서를 재정의 해서 주어진 문자열을 다시 재배치하는 문제이다. 따라서 dictionary에 order에 적힌 순서대로 알파벳의 순서를 다시 정하고, 그 순서에 따라 str을 다시 배치하면 된다.
order의 문자열을 가지고 문자의 순서를 dictionary에 저장하였다.{'a' : 1, 'b' : 2, 'c' : 3, ..., 'z' : 26}이지만 order에 정의된 순서대로 dictionary에 새로 정의한다. {'c' : 1, 'b' : 2, 'a' : 3}order에 없는 알파벳은 어느 위치에 들어가도 상관없으므로 그냥 처음부터 없는 문자는 결과에 집어넣어 준다.order의 길이)까지 돌리면서 str의 문자들을 처음부터 비교한다.str문자열을 돌면서 1번 순서인 알파벳을 결과에 추가하고 그 다음 2번 순서도 추가하고 마지막 순서인 알파벳까지 추가하면 끝