First Unique Character in a String using Java

0 min read 164 words

The challenge

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

Examples:

s = "spacesuite"
return 1.

s = "simplespacesuite"
return 2.

Note: You may assume the string contains only lowercase English letters.

The solution

class Solution {
    // take in a String and return an int containing the index
    public int firstUniqChar(String s) {
        // create a HashMap to hold our counts
        HashMap<Character, Integer> h = new HashMap<>();
        // get the string's length
        int len = s.length();
        
        // loop to populate the HashMap
        for(int i=0; i<len; i++) {
            // get the Character
            char c = s.charAt(i);
            // add or update HashMap entry
            h.put(c, h.getOrDefault(c, 0)+1);
        }
        
        // loop to look for non-duplicates
        for(int i=0; i<len; i++) {
            // get the Character
            char c = s.charAt(i);
            // if only have 1 item, then we found our match
            if (h.get(c)==1)
                return i;
        }
        
        // return -1 if all else fails
        return -1;
        
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts