题目描述:
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解题思路:
使用hashmap来存放每个字符出现的次数,返回第一次只出现一次字符在字符串中的下标。
代码(java):
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<str.length();i++){
if(map.keySet().contains(str.charAt(i))){
map.put(str.charAt(i),map.get(str.charAt(i))+1);
}
else{
map.put(str.charAt(i),1);
}
}
for(int i=0;i<str.length();i++){
if(map.get(str.charAt(i))==1)return i;
}
return -1;
}
}