Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
Note: You may assume the string contain only lowercase letters.
Solution
Create an Array of length 26 and maintain frequency of the each character. Here
After we build frequency Array, Just iterate a String one more time and check for each character, if frequency is 1 then that index is the answer.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class FirstUniqueCharacter { public int firstUniqChar(String s) { int a[] = new int[26]; for (char c : s.toCharArray()) { a[c - 'a']++; } for (int i = 0; i < s.length(); i++) { if (a[s.charAt(i) - 'a'] == 1) return i; } return -1; } public static void main(String[] args) { FirstUniqueCharacter frstUncCharObj=new FirstUniqueCharacter(); System.out.println(frstUncCharObj.firstUniqChar("leetcode")); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.