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));
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!