(二)字符串中的第一个唯一字符

题目描述:

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

示例:

提示:你可以假定该字符串只包含小写字母。


方案一:哈希表

class Solution {
    public int firstUniqChar(String s) {
    Map<Character,Integer> map = new HashMap<Character,Integer>(26);
    char[] chars = s.toCharArray();
    //遍历字符串,用散列表存入字符并计数
    for(char ch : chars){
        map.put(ch, map.getOrDefault(ch,0) + 1);
    }
    //遍历找计数为1的字符,输出下标
    for(int i = 0; i < chars.length; i++){
        if(map.getOrDefault(chars[i],0)==1)
        return i;
    }
    return -1;
    }
}

方案二:数组

class Solution {
    public int firstUniqChar(String s) {
    int[] counts = new int[26];
    char[] chars = s.toCharArray();
    //遍历字符串,用数组存入字符并计数
    for(char ch : chars){
        counts[ch - 'a']++;
    }
    //遍历找计数为1的字符,输出下标
    for(int i = 0; i < chars.length; i++){
        if(counts[chars[i] - 'a']==1)
        return i;
    }
    return -1;
    }
}

note:此题通过数组解决用的 时间  内存 开销较小


版权声明:本文为qq_39082486原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。