Skip to main content

Command Palette

Search for a command to run...

Custom Sort String

Published
1 min read
Custom Sort String
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

LeetCode Problem - 791

class Solution {
    // This method custom sorts the string `s` based on the order specified in `order`.
    public String customSortString(String order, String s) {
        // HashMap to store the frequency of each character in the string `s`
        HashMap<Character, Integer> freq = new HashMap<>();

        // Count the frequency of each character in the string `s`
        for (int i = 0; i < s.length(); i++) {
            char letter = s.charAt(i);
            freq.put(letter, freq.getOrDefault(letter, 0) + 1);
        }

        // StringBuilder to build the custom sorted string
        StringBuilder sb = new StringBuilder();

        // Append characters in the order specified in `order`
        for (char letter : order.toCharArray()) {
            if (freq.containsKey(letter)) {
                sb.append(String.valueOf(letter).repeat(freq.get(letter)));
                // Remove the character from the frequency map after appending
                freq.remove(letter);
            }
        }

        // Append remaining characters in `s` that are not in `order`
        for (char letter : freq.keySet()) {
            sb.append(String.valueOf(letter).repeat(freq.get(letter)));
        }

        // Return the custom sorted string
        return sb.toString();
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.