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.
分析:找出字符串中第一次出现且不重复的字符,返回其字符的下标,如果不存在就返回-1.
用hashMap进行求,hashMap中可以通过ey-value的存储位置对和位置,对数据进行标记
public int firstUniqChar(String s) {
Map<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(map.containsKey(c)){
map.put(c,-1);
}else{
map.put(c,1);
}
} for(int i=0;i<s.length();i++){
if(map.get(s.charAt(i))==1){
return i;
}
}
return -1;
}