Find the first character that appears exactly once in each input string, or report that there is none, using a 26-letter count array and two passes.
Solution
Main.java
public class Main {
static String firstUnique(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) return s.charAt(i) + " at " + i;
}
return "none";
}
public static void main(String[] args) {
for (String s : new String[]{"swiss", "programming", "aabbcc", "java"}) System.out.println(s + ": " + firstUnique(s));
}
}
Output Verified by compiling and running
swiss: w at 1
programming: p at 0
aabbcc: none
java: j at 0
The first pass counts, the second finds the earliest character with count 1 – O(n) time.
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!