题目
题目链接
解题思路
-
基本思路:
- 使用字典记录每个英文字符出现的次数。
- 遍历字符串,更新字符计数。
- 找到第一个出现三次的字符并返回。
-
实现方法:
- 遍历字符串,逐个字符更新计数。
- 检查计数是否达到三次。
- 返回第一个达到三次的字符。
代码
#include <iostream>
#include <unordered_map>
using namespace std;class Solution {
public:char firstCharThreeTimes(const string& str) {unordered_map<char, int> charCount;for (char c : str) {if (isalpha(c)) { // 只考虑字母charCount[c]++;if (charCount[c] == 3) {return c;}}}return '\0'; // 如果没有字符出现三次,返回空字符}
};int main() {string input;getline(cin, input);Solution solution;char result = solution.firstCharThreeTimes(input);if (result != '\0') {cout << result << endl;} else {cout << "No character appears three times." << endl;}return 0;
}
import java.util.*;public class Main {public static char firstCharThreeTimes(String str) {Map<Character, Integer> charCount = new HashMap<>();for (char c : str.toCharArray()) {if (Character.isLetter(c)) { // 只考虑字母charCount.put(c, charCount.getOrDefault(c, 0) + 1);if (charCount.get(c) == 3) {return c;}}}return '\0'; // 如果没有字符出现三次,返回空字符}public static void main(String[] args) {Scanner sc = new Scanner(System.in);String input = sc.nextLine();char result = firstCharThreeTimes(input);if (result != '\0') {System.out.println(result);} else {System.out.println("No character appears three times.");}}
}
class Solution:def firstCharThreeTimes(self, s):char_count = {}for c in s:if c.isalpha(): # 只考虑字母char_count[c] = char_count.get(c, 0) + 1if char_count[c] == 3:return creturn None # 如果没有字符出现三次,返回Noneif __name__ == "__main__":input_str = input().strip()solution = Solution()result = solution.firstCharThreeTimes(input_str)if result is not None:print(result)else:print("No character appears three times.")
算法及复杂度
- 算法:字符计数
- 时间复杂度:\(\mathcal{O}(n)\),其中 \(n\) 为字符串长度
- 空间复杂度:\(\mathcal{O}(m)\),其中 \(m\) 为不同字符的数量