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.
我的方法采用了HashMap来储存集合,但是看了讨论后发现,对于已知种类数量的数据集合如26个字母,直接采用数组的形式储存是更好的方法。毕竟HashMap就是对未知集合进行标号方便查找。
public class Solution {
public int firstUniqChar(String s) {
int freq [] = new int[26];
for(int i = 0; i < s.length(); i ++)
freq [s.charAt(i) - 'a'] ++;
for(int i = 0; i < s.length(); i ++)
if(freq [s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
}