- 
                Notifications
    
You must be signed in to change notification settings  - Fork 0
 
387. First Unique Character in a String
        Jacky Zhang edited this page Aug 29, 2016 
        ·
        1 revision
      
    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.
解题思路为建立一个char-freq的mapping。 先将string转换为char[],可以比string.charAt(index)运行快。
public class Solution {
    public int firstUniqChar(String s) {
        char[] array = s.toCharArray();
        int[] freq = new int[26];
        for(int i = 0; i < s.length(); i++) {
            freq[array[i] - 'a']++;
        }
        for(int i = 0; i < s.length(); i++) {
            if(freq[array[i] - 'a'] == 1) return i;
        }
        return -1;
    }
}