Leetcode #791 Custom Sort String

Leetcode #791 Custom Sort String

Difficulty: Medium

This question is not too difficult.

Thought process:

  • First, we can find all occurrences of s based on order and replace with a space since we've used it
  • Replace the spaces and append the remaining characters to the result set.

Time complexity: O(n^2)

Link:Custom Sort String

/**
 * @param {string} order
 * @param {string} s
 * @return {string}
 */
var customSortString = function(order, s) {
    let res = "";


    for(let i=0;i<order.length;i++){
        for(let j=0; j<s.length;j++){
            if(s[j] == order[i]){
                res += s[j];
                s = s.replace(s[j], ' ');
            }
        }
    }

    s = s.replace(/\s/g, '');
    res += s.trim();

    return res;
};