1. 程式人生 > >劍指offer34 第一個只出現一次的字元(java)

劍指offer34 第一個只出現一次的字元(java)

題目

在一個字串(1<=字串長度<=10000,全部由字母組成)中找到第一個只出現一次的字元,並返回它的位置

思路

建立一個雜湊表,第一次掃描的時候,統計每個字元的出現次數。第二次掃描的時候,如果該字元出現的次數為1,則返回這個字元的位置。

程式碼

public static int FirstNotRepeatingChar(String str){
	int l=str.length();
	HashMap<Character, Integer> map=new HashMap<>();
	for(int i=0;i<l;i++){
		if(map.containsKey(str.charAt(i))){
			int tem=map.get(str.charAt(i));
			map.remove(str.charAt(i));
			map.put(str.charAt(i), tem+1);
		}else{
			map.put(str.charAt(i), 1);
		}
	}
	for(int j=0;j<l;j++){
		if(map.get(str.charAt(j))==1)
			return j;
	}
	return 0;
}