First Unique Character in a String Java - The Coding Shala

Home >> Interview Questions >> first unique character in a string

First Unique Character in a String

In this post, you will learn how to find the first unique character in a given string in Java.

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"

return 0.

s = "loveleetcode",
return 2.

First Unique Character in a String Solution

Approach 1:

We can use HashMap. We Count every character's frequency and store it as value. Again check with string's char and if the value in the map is one return its index.
Java Program: 

class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i = 0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)) map.put(ch, map.get(ch)+1);
            else map.put(ch, 1);
        }
        for(int i=0;i<s.length();i++){
            if(map.get(s.charAt(i)) == 1) return i;
        }
        return -1;
    }
}

Approach 2:
We can make the string to char array. If a character's index is its last Index in the array then return its index.
Java Program: 

class Solution {
    public int firstUniqChar(String s) {
        char[] a = s.toCharArray();
  
  for(int i=0; i<a.length;i++){
   if(s.indexOf(a[i])==s.lastIndexOf(a[i])){return i;}
  }
  return -1;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala