Custom Sort String

Medium~15 min

You are given two strings: order and s.

All characters of order are unique and define a custom ordering of lowercase letters.

Rearrange the characters of s so that they match the ordering defined by order. Specifically:

  • Characters that appear in order should be sorted according to their position in order
  • Characters that do not appear in order should be placed at the end of the result, in their original relative order from s

Return the rearranged string.

Examples

Example 1
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation: c, b, and a appear in order, so they are placed first in that order. d is not in order and goes at the end.
Example 2
Input: order = "bcafg", s = "abcd"
Output: "bcad"
Explanation: b, c, a are reordered per order. f and g from order do not appear in s. d is not in order and goes at the end.
Example 3
Input: order = "xyz", s = "hello"
Output: "hello"
Explanation: None of the characters in s appear in order, so the original order of s is preserved.

Constraints

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters
  • All characters in order are unique
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run