在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).(從0開始計數)
前兩天剛寫過一個題,統計數組中只出現一次的數字。鏈接在這裏
當時的思想是用HashSet來存儲<Integer>,遍歷,如果衝突了,說明裏面有,就刪掉。不衝突的話,就放裏面。這樣遍歷完的時候,裏面剩的,就是隻出現1次的元素。
本次思路,用hashmap存<Character,,Integer>,存完之後遍歷,等於1的時候直接返回。
import java.util.HashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str == null || str.length() == 0){
return -1;
}
int len = str.length();
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < len; i++){
char c = str.charAt(i);
if(!map.containsKey(c)){
map.put(c,1);
}else{
map.put(c, map.get(c) + 1);
}
}
for(int i = 0; i < len; i++){
if(map.get(str.charAt(i)) == 1){
return i;
}
}
return -1;
}
}