leetcode刷题---字符串---字符串中的第一个唯一字符

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

示例:

s = “leetcode”
返回 0

s = “loveleetcode”
返回 2

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

在那道题之后先想到了用map来写,一开始就用了一个map来记录字母出现的数量,然后在解决第一个唯一的问题时卡壳了。当时想得遍历map得到所有value为1的字母,然后用来遍历字符串,第一个匹配的上的就是第一个唯一字母。
看了题解之后发现自己太蠢了,没想到直接遍历字符串来作为key取出map的value,如果value是1不就说明是第一个唯一字母。长个教训。

class Solution {
    
    
    public int firstUniqChar(String s) {
    
    
        char[]chs = s.toCharArray();
        Map<Character,Integer> count=new HashMap();
        for(int i=0;i<chs.length;i++){
    
    
             count.put(chs[i], count.getOrDefault(chs[i], 0) + 1);
        }
        for(int i=0;i<chs.length;i++){
    
    
            if(count.get(chs[i])==1)return i;
        }
     return -1;
    }
}

这种方法的时间复杂度和空间复杂度都不算得上理想,所以去找了评论大哥的用数组一次遍历就完成的方法。
首先设置一个26长度的整形数组,用于记录每个字符在之前是否出现,如果出现了设置为1。
然后遍历字符串,如果judgeArray[c - ‘a’] == 1 代表之前出现过,所以继续下一次循环
如果judgeArray[c - ‘a’] == 0,则继续找当前字符在字符串后面是否存在,如果不存在,返回当前字符的索引
如果存在,则把judgeArray[c - ‘a’] 设置为1.

class Solution {
    
    
    public int firstUniqChar(String s) {
    
    
        if(s.length() == 1) {
    
    
            return 0;
        }
        int[] judgeArray = new int[26];
        int index = -1;
        for (int i = 0; i < s.length(); i++) {
    
    
            char c = s.charAt(i);
            if(judgeArray[c - 'a'] == 1) {
    
    
                continue;
            }else {
    
    
                int tempIndex = s.indexOf(c, i + 1);
                if(tempIndex == -1) {
    
    
                    index = i;
                    return index;
                }else {
    
    
                    judgeArray[c - 'a'] = 1;
                }
            }
        }
        return index;
    }
}


作者:bobby996
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/387ti-8788-6963-by-bobby996-k5uh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/weixin_46428711/article/details/111224494