题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置;
解题思路
1.遍历给定的字符串,用一个int数组统计字符出现的次数;
2.再遍历给定的字符串,返回第一个只出现一次的字符的位置即可;
public int FirstNotRepeatingChar(String str) {
if (str == null || str.isEmpty()){
return -1;
}
int[] hash = new int[256];
for (int i=0; i<str.length(); i++){
hash[str.charAt(i)]++;
}
for (int i=0; i<str.length(); i++){
if (hash[str.charAt(i)] == 1){
return i;
}
}
return -1;
}