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

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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

解法1:

两次遍历,第一次遍历先把字符和出现的次数存入map里, 第二次遍历取出map中次数为1的第一个字符;

class Solution {
    public int firstUniqChar(String s) {
        char[] chars = s.toCharArray();
        Map<Character, Integer> map = new HashMap();
        
        for(Character c:chars) {
            //频率统计
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        for (int i = 0; i < chars.length; i++) {
            if(map.get(chars[i])==1) return i;//找到词频为1的字母(只出现一次)返回其索引
        }
        return -1;

    }
}

解法2:

利用 Java 字符串indexOf函数实现

class Solution {
    public int firstUniqChar(String s) {
        int res = s.length();
        for (int i = 'a'; i <= 'z'; i++) {
            int firstIndex = s.indexOf((char)i);
            if (firstIndex == -1) continue;
            int lastIndex = s.lastIndexOf((char)i);
            if (firstIndex == lastIndex) {//两次索引值相同则证明该字母只出现一次
                res = Math.min(firstIndex, res);//res 为只出现一次的字母中索引值最小的
            }
        }
        return res == s.length() ? -1 : res;
    }
}
发布了196 篇原创文章 · 获赞 212 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/kangbin825/article/details/104936658