首页 > 其他 > 详细

【嘎】字符串-字符串中的第一个唯一字符

时间:2020-04-27 15:12:45      阅读:58      评论:0      收藏:0      [点我收藏+]

题目:

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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;
    }
}

 

【嘎】字符串-字符串中的第一个唯一字符

原文:https://www.cnblogs.com/utomboy/p/12786193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!