问题:
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.
解决:
① hash table。
class Solution {//20ms
public int firstUniqChar(String s) {
int[] hash = new int[26];
for (char c : s.toCharArray()){
hash[c - 'a'] ++;
}
for (int i = 0;i < s.length();i ++){
if (hash[s.charAt(i) - 'a'] == 1){
return i;
}
}
return -1;
}
}
② 使用String类封装的方法。
class Solution { //9ms
public int firstUniqChar(String s) {
int res = s.length();
for (char c = 'a';c <= 'z';c ++){
int start = s.indexOf(c);
if (start == -1) continue;
if (start == s.lastIndexOf(c)){
res = Math.min(res,start);
}
}
return res == s.length() ? -1 : res;
}
}