387. First Unique Character in a String

原題網址:https://leetcode.com/problems/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.


方法:直方圖頻率統計。

public class Solution {
    private int[] frequency(String s) {
        int[] f = new int[26];
        char[] sa = s.toCharArray();
        for(char ch : sa) {
            f[ch - 'a'] ++;
        }
        return f;
    }
    public int firstUniqChar(String s) {
        int[] fs = frequency(s);
        for(int i = 0; i < s.length(); i ++) {
            if (fs[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章