Custom Sort String: Modified BubbleSort
Problem is here (#416th in my solved list): https://leetcode.com/problems/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 most26
, and no character is repeated inS
.T
has length at most200
.S
andT
consist of lowercase letters only.
public class Solution { public string CustomSortString(string S, string T) { Hashtable order = new Hashtable(); for (int i = 0; i < S.Length; i++) { order.Add(S[i], S.Length - i); } StringBuilder sb = new StringBuilder(T); int left = 0; int right = T.Length - 1; for (int i = 0; i < T.Length; i++) { if (order.ContainsKey(T[i])) { sb[left++] = T[i]; } else { sb[right--] = T[i]; } } bool sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < T.Length - 1; i++) { if (order.ContainsKey(sb[i]) && order.ContainsKey(sb[i + 1]) && (int)order[sb[i]] < (int)order[sb[i + 1]]) { char temp = sb[i]; sb[i] = sb[i + 1]; sb[i + 1] = temp; sorted = false; } } } return sb.ToString(); } }
Since S has at most 26 chars I didn't even bother to build an index and perform "slow" searches:
ReplyDeleteclass Solution:
def customSortString(self, S: str, T: str) -> str:
return "".join(sorted(T, key=lambda char: S.find(char)))
And we've got a one-liner :)
actually this can be made shorter:
Deleteclass Solution:
def customSortString(self, S: str, T: str) -> str:
return "".join(sorted(T, key=S.find))
Missed you, my friend!!! Solid as always, I missed the fact that |S| <= 26, which simplifies things a lot indeed
ReplyDeletethere was some problem with blogger that was preventing me from commenting, but now looks like things are back to normal, so be ready for my spam ) The fact that we have such a small alphabet also can be leveraged to build a very efficient array based index.
DeleteThanks for your solutions! Looking forward for the next one!