zoukankan      html  css  js  c++  java
  • 力扣(LeetCode)字符串中的第一个唯一字符 个人题解

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

    案例:

    s = "leetcode"
    返回 0.
    
    s = "loveleetcode",
    返回 2.
    

    注意事项:您可以假定该字符串只包含小写字母。

    这题的思想还是比较简单明了的,通过hashmap记录所有的键值对应关系,即字符出现的次数,然后再回过头循环一遍来判断出现的次数是否符合题意。

    要循环两次,空间和时间上都差强人意,但是是比较清晰的办法。

    而且通过评论区的提醒,当字符串足够长且出现的重复次数比较集中时,这种方法反而会带来空间和时间上的优势。

    代码如下:

    import java.util.HashMap;
    
    class Solution {
        public int firstUniqChar(String s) {
            HashMap<Character, Integer> map=new HashMap<Character,Integer>();
            for(int i=0;i<s.length();i++)
            {
                Character character=s.charAt(i);
                if(map.get(character)==null)
                    map.put(character, 1);
                else
                    map.put(character, map.get(character)+1);
            }
            for(int i=0;i<s.length();i++)
            {
                Character character=s.charAt(i);
                if(map.get(character)==1)
                    return i;
            }
            return -1;
        }
    }
  • 相关阅读:
    练习二(米奇老鼠)
    Photoshop笔记一
    HTML笔记1
    用IDEA写出第一个java web
    TCP协议怎么关闭?
    Sql Server2008R2与IDEA的连接
    通过HttpServer向Prometheus暴露端点
    了解Prometheus到底是什么?
    SPI扩展机制在框架中的使用
    motan系列1——与spring的集成原理
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/10433567.html
Copyright © 2011-2022 走看看