本文主要是介绍Leetcode 3121. Count the Number of Special Characters II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- Leetcode 3121. Count the Number of Special Characters II
- 1. 解题思路
- 2. 代码实现
- 题目链接:3121. Count the Number of Special Characters II
1. 解题思路
这一题算是一个分类讨论的问题吧,我们只需要对每一个字符考察其前序当中所有出现过的字符即可:
- 如果一个字母为小写字母,那么如果之前出现过该字符的大写字母,那么该字母必然不可能为special
- 如果一个字母为大写字母,如果前序出现过其小写字母,且未出现过上一类情况,那么可以将其记录为special
我们遍历一轮字符串,即可得到我们最终的答案。
2. 代码实现
给出python代码实现如下:
class Solution:def numberOfSpecialChars(self, word: str) -> int:status = [0 for _ in range(26)]seen = set()for ch in word:if ch in string.ascii_lowercase:idx = ord(ch) - ord('a')if string.ascii_uppercase[idx] in seen:status[idx] = -1else:idx = ord(ch) - ord('A')if string.ascii_lowercase[idx] in seen and status[idx] == 0:status[idx] = 1seen.add(ch)return Counter(status)[1]
提交代码评测得到:耗时322ms,占用内存18.5MB。
这篇关于Leetcode 3121. Count the Number of Special Characters II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!