题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
http://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
// 一些特殊情况的处理
if (0 == str.length()) {
return -1;
}
if (1 == str.length()) {
return 0;
}
HashMap<Character, Integer> hashMap = new HashMap<>();
char[] chrs = str.toCharArray();
for (char chr : chrs) {
int num = hashMap.getOrDefault(chr, 0);
num++;
hashMap.put(chr, num);
}
int res = -1;
for (int i = 0; i < chrs.length; i++) {
char chr = chrs[i];
int num = hashMap.get(chr);
if (num == 1) {
res = i;
break;
}
}
return res;
}
}