Sort Words by a Custom Alphabet
Problem statement
You are given a custom alphabet order and an array of lowercase words. Sort the words lexicographically under that custom order.
Compare the first position where two words differ using the characters' ranks in alphabet. If one word is a prefix of the other, the shorter word comes first. Return the sorted words.
Function
sortWordsByAlphabet(alphabet: String, words: String[]) → String[]Examples
Example 1
alphabet = "zyxwvutsrqponmlkjihgfedcba"words = ["apple","app","banana"]return = ["banana","app","apple"]Under the reversed alphabet, b precedes a. Among the two a-words, app is a prefix of apple.
Example 2
alphabet = "bacdefghijklmnopqrstuvwxyz"words = ["ab","aa","ba","b"]return = ["b","ba","ab","aa"]b-words come before a-words; prefixes come first; and within the a-words, the second character b ranks before a.
Example 3
alphabet = "abcdefghijklmnopqrstuvwxyz"words = []return = []An empty word array remains empty.
Constraints
alphabetis a permutation of the 26 lowercase English letters.0 <= words.length <= 100000.- Every word is nonempty and contains only lowercase English letters.
- The total number of characters across
wordsis at most200000.