Remove duplicate characters from a string using LinkedHashSet

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Input: s = "bcabc"
Output: "abc"

Convert the string to an array of char, and store it in a LinkedHashSet. This will preserve your ordering, and remove duplicates. Something like:

class Solution {
    public String removeDuplicateLetters(String s) {
        String string = "bcabc";

        char[] chars = string.toCharArray();
        Arrays.sort(chars);
        Set<Character> charSet = new LinkedHashSet<Character>();
        for (char c : chars) {
            charSet.add(c);
        }

        StringBuilder sb = new StringBuilder();
        for (Character character : charSet) {
            sb.append(character);
        }
        System.out.println(sb.toString());
        return sb.toString();
    }
}

Comments

Popular posts from this blog

Android - Using KeyStore to encrypt and decrypt the data

Stack and Queue

Java Reflection API