【算法训练】LeetCode#387 字符串中的第一个唯一字符
一、描述
387. 字符串中的第一个唯一字符
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode"
输出: 0
示例 2:
输入: s = "loveleetcode"
输出: 2
示例 3:
输入: s = "aabb"
输出: -1
二、思路
这道题主要是考察哈希表的操作,创建一个hashmap,key为每个字母,value是一个长度为2的数组,存储位置和出现次数。
(当然,因为这道题划分到了哈希表类型中,所以选择用哈希表做。如果用数组能更快。见v2)
三、解题
public class LeetCode387 {
public static int firstUniqChar(String s) {
HashMap<Character,int[]> map = new HashMap<>(); // key为字母,value[0]为其第一次的位置,value[1]为出现次数
char[] str = s.toCharArray();
for (int i = 0 ; i < str.length ; i++){
if (map.containsKey(str[i])){
int[] arr = map.get(str[i]);
if (arr[1] > 1){
// 如果已经两次以上了,就不浪费时间直接continue
continue;
}
arr[1] += 1;
map.put(str[i],arr);
} else {
// 未加入过
map.put(str[i],new int[]{i,1});
}
}
int ans = -1;
for (int[] arr : map.values()){
// 直接遍历value
if (arr[1] == 1){
if (arr[0] < ans || ans == -1){
ans = arr[0];
}
}
}
return ans;
}
// 方法二,用数组
public static int firstUniqCharV2(String s){
int[] arr = new int[26];
int n = s.length();
char[] chars = s.toCharArray();
for (int i = 0 ; i < n ; i++){
arr[chars[i]-'a']++; //记录次数
}
for(int i = 0 ; i < n ; i++){
if (arr[chars[i]-'a'] == 1){
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "leetcode";
System.out.println(firstUniqChar(str));
}
}

浙公网安备 33010602011771号