题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
//总感觉直接用HashMap好蠢...因为根本不需要存大于1个的元素,再探索看看有没有更好的解法
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int FirstNotRepeatingChar(String str) {
Map<Character,Integer>map=new HashMap<>();
char[]c=str.toCharArray();
for(int i=0;i<c.length;i++){
if(!map.containsKey(c[i]))
map.put(c[i],1);
else{
int count=map.get(c[i])+1;
map.put(c[i],count);
}
}
for (int i = 0; i < c.length; i++) {
if(map.get(c[i])==1)return i;
}
return -1;
}
}