美文网首页ACM题库~
[LeetCode]First Unique Character

[LeetCode]First Unique Character

作者: AceCream佳 | 来源:发表于2016-08-23 07:34 被阅读67次

题目:

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:

s = "leetcode"
return 0.
s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

这道题看似简单,其实还是容易碰到一些平时不在意的用法的。晚上熄灯前我来补上解题过程~~~

思路:

此题思路和前面勒索信那题的思路有相同的地方,都是利用了map
不过这题在leetcode上不能用,主要好像leetcode没有Entry。经过测试还是可以使用的。具体不用entry的方法我会想办法~

代码:

public int firstUniqChar(String s) {
        Map<Character, Integer> map = new LinkedHashMap<>(s.length());  
        for (char c : s.toCharArray()) {  
            if (map.containsKey(c)) {
                map.put(c, map.get(c)+1);
            }else {
                map.put(c, 1);
            }
        }  
        for (Entry<Character, Integer> entry : map.entrySet()) {  
            if (entry.getValue() == 1) {  
                return s.indexOf(entry.getKey());  
            }  
        }  
        return 0;
    }

相关文章

网友评论

    本文标题:[LeetCode]First Unique Character

    本文链接:https://www.haomeiwen.com/subject/lbigsttx.html