leetcode.com/problems/custom-sort-string/

 

Custom Sort String - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

 

class Solution {
	public String customSortString(String S, String T) {
		StringBuilder solution = new StringBuilder();

		int[] charCheck = new int[26];

		for (char temp : T.toCharArray()) {
			charCheck[temp - 'a']++;
		}

		for (char temp : S.toCharArray()) {
			while (charCheck[temp - 'a']-- > 0) {
				solution.append(temp);
			}
		}

		for (char temp = 'a'; temp <= 'z'; temp++) {
			while (charCheck[temp - 'a']-- > 0) {
				solution.append(temp);
			}
		}

		return solution.toString();
	}
}

+ Recent posts