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

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;
}

总结

通过以上的三个方法的题解学习,做算法题除了数据结构的内容,还需要对语言的基础上要掌握扎实。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值