LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Java String Programs · Question 9

Remove duplicate characters from a string in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Remove repeated characters from strings, keeping only the first occurrence of each, using a boolean array for seen characters.

Solution
Main.java
public class Main {
    static String dedupe(String s) {
        boolean[] seen = new boolean[128];        // ASCII
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (!seen[c]) {
                seen[c] = true;
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        for (String s : new String[]{"programming", "mississippi", "aAbBaA", "abc"}) System.out.println(s + " -> " + dedupe(s));
    }
}

Output Verified by compiling and running

programming -> progamin
mississippi -> misp
aAbBaA -> aAbB
abc -> abc

The char itself indexes the seen array – O(n) time. Upper and lower case are different characters.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links