387. 字符串中的第一个唯一字符
本题使用的是Java语言
题目描述
给定一个字符串 s
,找到 它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1
。
示例 1:
输入: s = “leetcode”
输出: 0
示例 2:
输入: s = “loveleetcode”
输出: 2
示例 3:
输入: s = “aabb”
输出: -1
方法一
首先想到就是使用hash来存储,将没有重复的字符包括对应下标进行存储,遇到重复的就存储字符以及修改后的下标
最后再做一次循环检验不为1的就是第一个不是重复的字符
public static int firstUniqChar(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
int t = 0;
if (map.containsKey(s.charAt(i))){
map.put(s.charAt(i),++t);
continue;
}
map.put(s.charAt(i),0);
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i))!=1){
return i;
}
}
return -1;
}
方法二
使用hash+队列的方法来做,原理就是将不是重复的放入队列,重复的给移除队列,最后如果数据都是重复的做一次判空即可。
public static int firstUniqChar(String s){
HashMap<Character, Integer> map = new HashMap<>();
LinkedList<Pair<Character,Integer>> queue = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (!map.containsKey(ch)){
map.put(ch,i);
queue.offer(new Pair<>(ch,i));
}else {
map.put(ch,-i);
while (!queue.isEmpty() && map.get(queue.peek().getKey()) <= -1 ){
queue.remove();
}
}
}
return queue.isEmpty() ? -1 : queue.getFirst().getValue();
}
方法三
这个方法的做法其实更简洁的一点没那么多的代码量,通过字符串的indexOf()方法和lastIndexOf()方法对左右字符串进行遍历,当两者不相等时,说明该字符是重复的,相等说明是唯一值。
public static int firstUniqChar(String s){
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (s.indexOf(ch) == s.lastIndexOf(ch)) {
return i;
}
}
return -1;
}
总结
通过以上的三个方法的题解学习,做算法题除了数据结构的内容,还需要对语言的基础上要掌握扎实。