题目描述:
在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置。
思路:
第一个只出现一次的字符是关键,就意味着需要所有的字符进行出现次数的统计,所以我们需要两次遍历:第一次获取每个字符出现的次数;第二次把第一个只出现一次的字符找到。在Java中可以通过HashMap实现对每个字符次数的统计,由于在题目中并没有我们限定使用Java提供的内置结构,所以可以通过这种办法迅速找到第一个只出现一次的字符。
算法实现:
import java.util.HashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str == null||str.equals("")) return -1;
char[] ch = str.toCharArray();
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0;i<ch.length;i++){
if(!map.containsKey(ch[i])){
map.put(ch[i],1);
}else{
map.put(ch[i],map.get(ch[i])+1);
}
}
for(int i=0;i<ch.length;i++ ){
if(map.get(ch[i])==1){
return i;
}
}
return -1;
}
}