First Unique Character in a String using Java

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; } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments