题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)
思路:
1.使用hashMap,键值对key存储字符,value存储出现次数。先遍历字符串,将字符存储到hashMap中
2.再遍历一遍字符串,如果hashMap中对应字符串的value值为1,即只出现一次,返回字符串遍历到的位置,遍历结束;遍历完都没有,返回-1.
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str==null) return -1;
//采用hashMap存储字符-次数对
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0;i<str.length();i++) {//将字符串放到hashMap中
if(map.containsKey(str.charAt(i))) {//如果已经包含
int time = map.get(str.charAt(i))+1;
map.put(str.charAt(i), time);
}else {
map.put(str.charAt(i), 0);
}
}
for(int i = 0;i<str.length();i++) {
if(map.get(str.charAt(i))==0)
return i;
}
return -1;
}
}