一、题目
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
1.1 思路
方法一:哈希表
1、将字符当成哈希表中的key,第一次出现时候为true,重复出现则置为false;
2、遍历数组,拿到第一个在哈希表中的value为true的字符。
1.2 代码
public class FirstNotRepeatingChar {
// google 4
public static int FirstNotRepeatingChar(String str) {
HashMap<Character, Boolean> map = new HashMap<>();
char[] chars = str.toCharArray();
// 重复的为false 不重复的为true
for (char c : chars){
if (map.containsKey(c)){
map.put(c,false);
}else {
map.put(c,true);
}
}
// 返回第一个不重复的
for (int i = 0; i < chars.length; i++) {
if (map.get(chars[i])){
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "google";
System.out.println(FirstNotRepeatingChar(str));
}
}
1.4 复杂度分析
时间复杂度 O(N)。N为字符串的长度,因为需要遍历两轮字符串,所以为2N,使用大O表示法则为O(N)。
空间复杂度 O(1)。使用到的辅助空间为哈希表的空间,由于题目给出所出现的字符为大小写字母,所以也就是说只需要占用O(32)的空间,则空间复杂度为O(1),常数级别。