【每日一题Day74】LC2351第一个出现两次的字母 | 哈希表 位运算

简介: 思路:使用哈希表统计出现的字母及其次数,当某个字母出现次数为2时立即返回

第一个出现两次的字母【LC2351】


Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:


  • A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.


  • s will contain at least one letter that appears twice.


新年快乐~


哈希表


  • 思路:使用哈希表统计出现的字母及其次数,当某个字母出现次数为2时立即返回


  • 实现


class Solution {
    public char repeatedCharacter(String s) {
        int[] charToCount = new int[26];
        for (int i = 0; i < s.length(); i++){
            charToCount[s.charAt(i) - 'a']++;
            if (charToCount[s.charAt(i) - 'a'] == 2){
                return s.charAt(i);
            }
        }
        return 0;
    }
}


。复杂度


  • 时间复杂度:O ( n ) ,n为字符串长度
  • 空间复杂度:O ( 1 )


位运算


  • 思路:使用int类型变量代替哈希表,当一个已经出现过的字母再次出现时立即返回


  • 实现


class Solution {
    public char repeatedCharacter(String s) {
        int state = 0;
        for (int i = 0; i < s.length(); i++){
            int t = 1 << (s.charAt(i) - 'a');
            if ((state & t ) != 0){
                return s.charAt(i);
            }
            state |= t;
        }
        return 0;
    }
}


。复杂度


  • 时间复杂度:O ( n ) ,n为字符串长度
  • 空间复杂度:O ( 1 )
目录
相关文章
|
2月前
【每日一题Day370】LC318最大单词长度乘积 | 哈希表 位运算
【每日一题Day370】LC318最大单词长度乘积 | 哈希表 位运算
35 1
|
2月前
【每日一题Day205】LC2441与对应负数同时存在的最大正整数 | 哈希表
【每日一题Day205】LC2441与对应负数同时存在的最大正整数 | 哈希表
29 1
|
2月前
【每日一题Day136】LC982按位与为零的三元组 | 哈希表
【每日一题Day136】LC982按位与为零的三元组 | 哈希表
24 0
|
2月前
|
存储
【每日一题Day158】LC2395和相等的子数组 | 哈希表
【每日一题Day158】LC2395和相等的子数组 | 哈希表
20 0
|
2月前
【每日一题Day203】LC1016子串能表示从 1 到 N 数字的二进制串 | 枚举 哈希表
【每日一题Day203】LC1016子串能表示从 1 到 N 数字的二进制串 | 枚举 哈希表
31 2
|
2月前
【每日一题Day317】LC2605从两个数字数组里生成最小数字 | 哈希表
【每日一题Day317】LC2605从两个数字数组里生成最小数字 | 哈希表
23 0
|
2月前
【每日一题Day368】LC421数组中两个数的最大异或值 | 字典树
【每日一题Day368】LC421数组中两个数的最大异或值 | 字典树
20 0
|
2月前
【每日一题Day252】LC1两数之和 | 哈希表
【每日一题Day252】LC1两数之和 | 哈希表
24 0
|
2月前
【每日一题Day142】LC1590使数组和能被 P 整除 | 前缀和+哈希表
【每日一题Day142】LC1590使数组和能被 P 整除 | 前缀和+哈希表
27 0
|
2月前
|
存储
【每日一题Day352】LC1726同积元组 | 哈希表+排列组合
【每日一题Day352】LC1726同积元组 | 哈希表+排列组合
19 0