第一个出现两次的字母【LC2351】
Given a string
sconsisting of lowercase English letters, return the first letter to appear twice.Note:
- A letter
aappears twice before another letterbif the second occurrence ofais before the second occurrence ofb.swill 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)O(n)O(n),n为字符串长度
- 空间复杂度:O(1)O(1)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)O(n)O(n),n为字符串长度
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

该文介绍了两种方法来解决找到给定字符串中第一个出现两次的字母的问题。第一种方法使用哈希表,当遇到字母的计数达到2时返回。第二种方法利用位运算,通过int变量记录已出现的字母。两种方法的时间复杂度均为O(n),空间复杂度为O(1)。

被折叠的 条评论
为什么被折叠?



