在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
因为关于重复,所以用HashMap,又因为要有序,所以采用LinkedHashMap。
import java.util.LinkedHashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
LinkedHashMap<Character,Integer> hp = new LinkedHashMap<>();
for(int x = 0;x<str.length();x++){//遍历字符串,若某个字符出现多次则将该字符对应值加1,否则设为1
if(hp.containsKey(str.charAt(x))){
int sum = hp.get(str.charAt(x));
sum ++;
hp.put(str.charAt(x),sum);
}else{
hp.put(str.charAt(x),1);
}
}
for(int i = 0;i<str.length();i++){//遍历字符串字符,将得到的字符与LinkedHashMap对应的键进行比对,若该键的值为1,则直接返回索引,否则返回-1
char a = str.charAt(i);
if((hp.get(a))==1){
return i;
}
}
return -1;
}
}