zoukankan      html  css  js  c++  java
  • 【嘎】字符串-字符串中的第一个唯一字符

    题目:

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

    案例:

    s = "leetcode"
    返回 0.

    s = "loveleetcode",
    返回 2.

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string

    解答:

    用hashmap存字符串和对应位置,因为hashmap无序,就又用了list,重复的就把list里面的去掉,没有的就往list里面加,最后list里面留下来的第一个就是要的那个字符

    class Solution {
       public int firstUniqChar(String s) {
            int res = -1;
            Map<String, String> map = new HashMap<String , String>();
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < s.length(); i++) {
                String str = s.charAt(i) + "";
                if (map.keySet().contains(str)) {
                    list.remove(str);
                } else {
                    map.put(str, i + "");
                    list.add(str);
                }
            }
            if (list.size() == 0) {
                res = -1;
            } else {
                String key = list.get(0);
                String intstr = map.get(key);
                res = Integer.parseInt(intstr);
            }
            return res;
        }
    }

    嗯 果然 很慢~~

    然后看到个简单粗暴的解法,直接判断首次和末次出现的位置,好酷~

    class Solution {
        public int firstUniqChar(String s) {
            for(int i=0; i<s.length(); i++){
                int first = s.indexOf(s.charAt(i));
                int last = s.lastIndexOf(s.charAt(i));
                if(first ==  last){
                    return i;
                }
            }
            return -1;
        }
    }
    越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙
  • 相关阅读:
    [HEOI2016/TJOI2016]树
    luogu P4198 楼房重建
    [USACO11DEC]Umbrellas for Cows
    luogu P2700 逐个击破
    一、MegaCli命令介绍
    dmidecode -t1 | egrep "Manufacturer|Product Name"
    IPMITOOL常用操作指令V1.0
    CentOS 7上的性能监控工具
    Could not open device at /dev/ipmi0
    n95医用口罩(常见型号1860 或者9132)防水无呼吸阀
  • 原文地址:https://www.cnblogs.com/utomboy/p/12786193.html
Copyright © 2011-2022 走看看