LeetCode_字符串_简单_387. 字符串中的第一个唯一字符
2023-09-27 14:25:46 时间
1.题目
给定一个字符串 s ,找到它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = “leetcode”
输出: 0
示例 2:
输入: s = “loveleetcode”
输出: 2
示例 3:
输入: s = “aabb”
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/first-unique-character-in-a-string
2.思路
(1)哈希表
使用哈希表存储 s 中每一种字符出现的次数,然后找出 hashmap 中出现次数为 1 的字符,并返回其下标即可。若不存在唯一字符,返回 -1
(2)数组计数
由于字符串 s 中只包含小写字母,所以可以使用长度为 26 的数组 freq 来存储每个字符在 s 中出现的次数,其中 freq[0] 存储 a 出现的次数,freq[1] 存储 b 出现的次数,以此类推。然后再遍历数组 freq,找出现次数为 1 的字符,并返回其下标。若不存在唯一字符,返回 -1。
3.代码实现(Java)
//思路1————哈希表
class Solution {
public int firstUniqChar(String s) {
//hashmap 用于存储字符串 s 中每一种字符出现的次数
Map<Character, Integer> hashmap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
hashmap.put(c, hashmap.getOrDefault(c, 0) + 1);
}
//找出 hashmap 中出现次数为 1 的字符,并返回其下标即可
for (int i = 0; i < s.length(); i++) {
if (hashmap.get(s.charAt(i)) == 1) {
return i;
}
}
//若不存在唯一字符,返回 -1
return -1;
}
}
//思路2————数组计数
class Solution {
public int firstUniqChar(String s) {
/*
字符串 s 中只包含小写字母,故使用长度为 26 的数组 freq 来存储每个字符在 s 中出现的次数
freq[0]存储 a 出现的次数,freq[1]存储 b 出现的次数,以此类推。
*/
int[] freq = new int[26];
int length = s.length();
for (int i = 0; i < length; i++) {
freq[s.charAt(i) - 'a']++;
}
for (int i = 0; i < length; i++) {
//如果找到只出现一次的字符,直接返回其下标即可
if (freq[s.charAt(i) - 'a'] == 1) {
return i;
}
}
//不存在唯一字符,返回 -1
return -1;
}
}
相关文章
- 【LeetCode】最小栈 [M](栈)
- 【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix(螺旋矩阵)】
- LeetCode_原地哈希_困难_41.缺失的第一个正数
- LeetCode_BFS_困难_864.获取所有钥匙的最短路径
- LeetCode_哈希表_排序_中等_451.根据字符出现频率排序
- LeetCode_DFS_中等_1254. 统计封闭岛屿的数目
- LeetCode_回溯_中等_78.子集
- LeetCode·每日一题·775.全局倒置与局部倒置·模拟
- LeetCode·每日一题·1619.删除某些元素后的数组均值·排序·数学
- LeetCode·每日一题·1374.生成每种字符都是奇数个的字符串·模拟
- LeetCode·每日一题·1403.非递增顺序的最小子序列·贪心
- LeetCode-202. 快乐数(java)
- LeetCode-171. Excel 表列序号(java)
- LeetCode-28. 实现strStr()(java)
- LeetCode-316. 去除重复字母&&1081.不同字符的最小子序列(Java实现)
- LeetCode-169. 多数元素(Goland实现)
- mysql学习 | LeetCode数据库简单查询练习
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- [LeetCode] 162. Find Peak Element 查找峰值元素
- [LeetCode] 153. Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值
- [LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串