题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思想:
Map<Character,Integer> map=new HashMap<>();
定义一个map,遍历集合判断并以字符为键,出现次数为值讲所有字符存入map中
第二次遍历找到第一个值为1得就返回;
代码:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int FirstNotRepeatingChar(String str) {
int res=-1;
Map<Character,Integer> map=new HashMap<>();
for(int i=0;i<=str.length()-1;i++){
map.put(str.charAt(i),map.get(str.charAt(i))==null?1:map.get(str.charAt(i))+1);
}
for(int i=0;i<str.length()-1;i++){
if (map.get(str.charAt(i))==1){
return i;
}
}
return res;
}
}