持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
一、题目描述:
387. 字符串中的第一个唯一字符 - 力扣(LeetCode) (leetcode-cn.com)
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode"
输出: 0
示例 2:
输入: s = "loveleetcode"
输出: 2
示例 3:
输入: s = "aabb"
输出: -1
提示:
- 1 <= s.length <= 10^5
- s 只包含小写字母
二、思路分析:
看到这道题,首先的思路暴力解决双层遍历,遍历过程中需要两个变量,分别记录字母出现的次数,另外一个就是判断是否全部都是重复的。
如果存在第一个不重复的字母,那遍历过程中肯定可以解决。
如果不存在,则用第二个变量来解决。
后面看了下大家提供的方案,利用hashmap确实清晰很多。
发现还是没有好好利用java里的一些工具,提高解决问题的能力。
哈希法如下
使用LinkedHashMap的数据结构的特点,有序,key不重复的性质。
如果重复,value为-1。
最后再遍历一次map,找出第一个不是-1的索引。如果都没有的话,最后返回-1。
三、AC 代码:
public class FirstUniqChar {
public static int firstUniqChar(String s) {
int m = 0; //记录返回值
int uniq = 0; //判断是否存在不重复的值
for (int j = 0; j < s.length(); j++) {
int u = 0; //记录重复的次数
for (int i = 0; i < s.length(); i++) {
if (s.charAt(j) == s.charAt(i)) {
u = u + 1;
}
if (u == 2) {
break;
}
}
if (u == 1) {
m = j;
break;
}else {
uniq = uniq + 1;
}
}
if (uniq == s.length()) {
m = -1;
}
return m;
}
class Solution {
public int firstUniqChar(String s) {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
Integer count = map.get(aChar);
if (count == null) {
map.put(aChar, i);
} else {
map.put(aChar, -1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() != -1) {
return entry.getValue();
}
}
return -1;
}
}