使用一个LinkedHashMap(迭代遍历时,按照插入的顺序遍历)和一个List,如果字母第一次出现,存入map中,并把位置存入List中,遍历map,找到第一个value为1的字母,返回List存储的位置。
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
char[] cha=str.toCharArray();
Map<Character,Integer> map=new LinkedHashMap<Character,Integer>();
ArrayList<Integer> index1=new ArrayList<Integer>();
for(int i=0;i<cha.length;i++)
{
if(map.containsKey(cha[i]))
{
map.put(cha[i], map.get(cha[i])+1);
}
else
{
map.put(cha[i], 1);
index1.add(i);
}
}
int i=0;
Object[] index2=index1.toArray();
for(Map.Entry<Character, Integer> entry:map.entrySet())
{
int value=entry.getValue();
if(value==1)
{
return Integer.parseInt(index2[i].toString());
}
i++;
}
return -1;
}
}