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.
Subscribe to see which companies asked this question.
用hash表存每个字符和其对应出现的次数。 第一次扫描是填满hash表,第二次扫描是获取第一个只出现一次的字符的位置。
/**
* 在一个字符串(1<=字符串长度<=10000,全部由字母组成) 中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始.
* 用hash表存每个字符和其对应出现的次数。
* 第一次扫描是填满hash表,第二次扫描是获取第一个只出现一次的字符的位置。
*/
public int firstUniqChar(String str) {
HashMap<Character, Integer> map = new HashMap<Character,Integer>();
int len = str.length();
if(len <= 0){
return -1;
}
char c ;
int num;
/*第一次扫描是填满hash表*/
for(int i = 0;i<len;i++){
num = 0;
c = str.charAt(i);
if(map.containsKey(c)){
num = map.get(c);
}
num ++;
map.put(c, num);
}
/*第二次扫描是获取第一个只出现一次的字符的位置。*/
for(int i = 0;i<len;i++){
c = str.charAt(i);
num = map.get(c);
if(num == 1){
return i;
}
}
return -1;
}