LeetCode387_387. 字符串中的第一个唯一字符

LeetCode387_387. 字符串中的第一个唯一字符

一、描述

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

示例 1:

输入: s = "leetcode"
输出: 0

示例 2:

输入: s = "loveleetcode"
输出: 2

示例 3:

输入: s = "aabb"
输出: -1

提示:

1 <= s.length <= 10的5次方
s 只包含小写字母

二、题解

方法一:

统计出来只出现一次的个数,然后找出最小的那个下标返回即可。

class Solution {
    
    
    public int firstUniqChar(String s) {
    
    
        int res = -1;
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < s.length(); i++) {
    
    
            map.put(s.charAt(i) + "", (map.get(s.charAt(i) + "") != null ? map.get(s.charAt(i) + "") + 1 : 1));//注意map中get的时候参数是String,不要用char
        }
        String temp = "";
        for (String key : map.keySet()) {
    
    
            if (map.get(key) == 1) {
    
    
                temp += key;
            }
        }
        if (temp.length() > 0) {
    
    
            int temp2 = s.length() - 1;
            for (int i = 0; i < temp.length(); i++) {
    
    
                temp2 = s.indexOf(temp.charAt(i)) < temp2 ? s.indexOf(temp.charAt(i)) : temp2;
            }
            res = temp2;
        }
        return res;
    }
}

LeetCode 367. 有效的完全平方数
LeetCode 371. 两整数之和
LeetCode 383. 赎金信
LeetCode 387. 字符串中的第一个唯一字符
LeetCode 389. 找不同
LeetCode 404. 左叶子之和
LeetCode 412. Fizz Buzz
LeetCode 414. 第三大的数
LeetCode 415. 字符串相加
LeetCode 434. 字符串中的单词数



声明:
        题目版权为原作者所有。文章中代码及相关语句为自己根据相应理解编写,文章中出现的相关图片为自己实践中的截图和相关技术对应的图片,若有相关异议,请联系删除。感谢。转载请注明出处,感谢。


By luoyepiaoxue2014

B站: https://space.bilibili.com/1523287361 点击打开链接
微博: http://weibo.com/luoyepiaoxue2014 点击打开链接

猜你喜欢

转载自blog.csdn.net/luoyepiaoxue2014/article/details/129992721
今日推荐