Saturday, April 29, 2017

387. First Unique Character in a String

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

s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.



Solution:

Since there are only lower case characters, we can use an array with size 26 as a hashmap to record the (character, frequency) mapping. The indices of the array are used as a mapping to the characters.

First round is to count the frequency of each character.

Second round is to find the first character with frequency == 1.

Since we only need to go through the input array two times, the time complexity is O(n).



Code:


public class Solution {
    public int firstUniqChar(String s) {
        int[] check = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            check[c - 'a']++;
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (check[c - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}