题目中有指明“全部是字母,区分大小写”。
构建映射表,一次遍历并记录。
public static int FirstNotRepeatingChar(String str) {
if(str==null) return -1;
boolean[] count=new boolean[58];//记录是否第一次出现
int[] position=new int[58];//记录第一次出现的位置
char[] characters=str.toCharArray();
int index=0;//用于指向字符在数组中的位置
int length=characters.length;
for(int i=0;i<length;i++){
index=characters[i]-65;//用较大的数组换取算法的便利,不需要判断大小写
//若字符首次出现,记录其位置
if(!count[index]&&position[index]>=0) {
count[index]=true;
position[index]=i;
}
//不是首次出现,标记
else if(count[index]) {
count[index]=false;
position[index]=-1;
}
}
//从记录中寻找答案
int answer=length;
for(int i=0;i<58;i++){
if(count[i]) answer=answer<position[i]?answer:position[i];
}
if(answer!=length) return answer;
else return -1;
}