Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode" 输出: 0 示例 2:
输入: s = "loveleetcode" 输出: 2 示例 3:
输入: s = "aabb" 输出: -1
提示:
1 <= s.length <= 105 s 只包含小写字母
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/fi… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、思路分析:
字符串计数问题,第一个不重复的字符, 可能存在多个不重复的字符,返回第一的索引,使用哈希的方法。
我们可以对字符串进行两次遍历。对于哈希中的每一个键值对,键表示一个字符,如果该字符只出现一次, 值表示它的首次出现的索引,如果该字符出现多次,值表示 -1,在第二次遍历时,我们只需要在哈希映射中的所有值中找出其中不为 -1 的最小值,即为第一个不重复字符的索引。如果哈希映射中的所有值均为 -1,我们就返回 -1。
三、AC代码
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> position = new HashMap<Character, Integer>();
int n = s.length();
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
if (position.containsKey(ch)) {
position.put(ch, -1);
} else {
position.put(ch, i);
}
}
int first = n;
for (Map.Entry<Character, Integer> entry : position.entrySet()) {
int pos = entry.getValue();
if (pos != -1 && pos < first) {
first = pos;
}
}
if (first == n) {
first = -1;
}
return first;
}
}
四、总结:
掘友们,解题不易,如果觉得有用就留下个赞或评论再走吧!谢啦~ 💐