题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1.
解题思路
用Hashmap,字符串中的字符作为key,出现的次数作为value。用到hashmap中的containsKey方法,判断hashmap中是否存在该key,存在则返回true,然后取到该key对应的value进行+1;不存在的话直接put进去即可。
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
int len = str.length();
if(len==0)
return -1;
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<len;i++){
if(map.containsKey(str.charAt(i))){
int value = map.get(str.charAt(i));
map.put(str.charAt(i),value+1);
}
else
map.put(str.charAt(i),1);
}
for(int j=0;j<len;j++){
if(map.get(str.charAt(j))==1)
return j;
}
return -1;
}
}