在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
思路:定义一个HashMap类型对象,遍历整个字符数组,并且将每个字符出现的次数保存在HashMap类型对象中。
import java.util.HashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
if(map.containsKey(c))
{
int time=map.get(c);
time++;
map.put(c,time);
}
else
{
map.put(c,1);
}
}
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
if(map.get(c)==1)
return i;
}
return -1;
}
}