题目描述:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
public class Solution {
/*
思路:考虑到这是求字符出现的次数,而字符时有限个数的,而且又涉及到字符是否重复出现,
因此考虑到用哈希表来记录字符是否出现过,那么我们用256长度的数组来表示256个字符,并
初始化为-1,表示还没有出现过,如果一个字符第一次出现,那么将字符对应的位置设为出现的
次序index,如果一个字符对应的位置大于等于0,那么将这个位置设置为,2,表示出现过不止
一次,字符串循环完毕后,找出大于0的最小的数字的位置对应的字符串就是第一个只出现一次
的字符串
*/
public int FirstNotRepeatingChar(String str) {
if(str == null || str.length() == 0){
return -1;
}
//int index = 0; //用来表示字符出现的顺序
int len = str.length();
int[] count = new int[256];
for(int i = 0; i<256;i++){
count[i] = -1;
}
for(int i=0; i<len; i++){
char c = str.charAt(i);
if(count[c] == -1){
count[c] = i;
}
else if(count[c] >=0 ){
count[c] = -2;
}
//index++;
}
int min = Integer.MAX_VALUE;
for(int j = 0; j<count.length; j++){
if(count[j]>=0){
if(count[j]<min){
min = count[j];
}
}
}
return min;
}
}