原题网址: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;
}
}