描述
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:0≤�≤100000≤n≤10000,且字符串只有字母组成。
要求:空间复杂度 �(�)O(n),时间复杂度 �(�)O(n)
示例1
输入:
"google"
复制
返回值:
4
复制
示例2
输入:
"aa"
复制
返回值:
-1
import java.util.HashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
HashMap<Character, Boolean> hashMap = new HashMap<Character, Boolean>();
char[] chars = str.toCharArray();
for (int index = 0; index < chars.length; index++) {
if (hashMap.containsKey(str.charAt(index))) {
hashMap.put(str.charAt(index), false);
} else {
hashMap.put(str.charAt(index), true);
}
}
for (int index1 = 0; index1 < chars.length; index1++) {
if (hashMap.get(str.charAt(index1))) {
return index1;
}
}
return -1;
}
}