Leetcode 791. Custom Sort String
You are given two strings, order
and s
. All the characters of order
are unique, and order
is a permutation of the characters in s
. Reorder the characters of s
so that they match the order that order
was sorted. More specifically, if a character x
appears before a character y
in order
, then x
should appear before y
in the reordered string.
Return any permutation of s
that respects this ordering.
Input: order = "cba", s = "abcd"
Output: "cbad"
order.length
<= 26s.length
<= 200order
and s
consist of lowercase English letters.order
are unique.s
will appear in order
?
order
is a permutation of the characters in s
.s
while sorting?
s
which are not in order
?
order
is a permutation of the characters in s
.s
.order
and append the characters from s
to the result based on their count.order
, append any remaining characters that are not included in the order
. But as per problem statement, this step won’t be necessary since order
is a permutation of characters present in s
.import java.util.HashMap;
public class CustomSortString {
public String customSortString(String order, String s) {
// Map to count frequency of characters in s
HashMap<Character, Integer> countMap = new HashMap<>();
for (char ch : s.toCharArray()) {
countMap.put(ch, countMap.getOrDefault(ch, 0) + 1);
}
StringBuilder result = new StringBuilder();
// Append characters as per the order
for (char ch : order.toCharArray()) {
if (countMap.containsKey(ch)) {
int count = countMap.get(ch);
for (int i = 0; i < count; i++) {
result.append(ch);
}
// Remove the character from the map once it is processed
countMap.remove(ch);
}
}
// Append remaining characters if any
// which should not exist per problem statement
for (char ch : countMap.keySet()) {
int count = countMap.get(ch);
for (int i = 0; i < count; i++) {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
CustomSortString sorter = new CustomSortString();
String order = "cba";
String s = "abcd";
System.out.println(sorter.customSortString(order, s)); // Output: "cbad"
}
}
s
.order
.The overall time complexity is O(n + m). Space complexity is O(n) for storing the frequency count.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?