LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Java String Programs · Question 2

First non-repeating character in a string in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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