-
发表于 2024.08.31
-
第一题比较简单,使用两个布尔数组分别记录小写字母和大写字母是否出现过。然后统计大小写都出现过的字母的数量即可。
第二题稍微复杂一点,需要用两个整型数组记录每个字母最后一个小写出现的位置和第一个大写出现的位置。然后遍历字母,如果某个字母的第一次大写出现位置在最后一次小写出现位置之后,那么这个字母就是特殊字母。
第一题做法:
class Solution { public: int numberOfSpecialChars(string word) { int has_lower[26] {false}; int has_upper[26] {false}; for (const auto& ch : word) { if (isupper(ch)) { has_upper[ch - 'A'] = true; } else { has_lower[ch - 'a'] = true; } } int ans = 0; // 统计大小写字母都出现过的字母数量 for (int i = 0; i < 26; ++i) ans += (has_lower[i] && has_upper[i]); return ans; } };
第二题的做法:
class Solution { public: int numberOfSpecialChars(string word) { int last_lower[26]; int first_upper[26]; fill(begin(last_lower), end(last_lower), -1); fill(begin(first_upper), end(first_upper), -1); for (int i = 0; i < word.size(); ++i) { auto ch = word[i]; if (isupper(ch)) { auto idx = ch - 'A'; // 记录第一次大写字母出现的位置 if (first_upper[idx] == -1) first_upper[idx] = i; } else { // 记录最后一次小写字母出现的位置 last_lower[ch - 'a'] = i; } } // 统计符合要求的字母的数量 int ans = 0; for (int i = 0; i < 26; ++i) { ans += ( first_upper[i] != -1 && last_lower[i] != -1 && first_upper[i] > last_lower[i] ); } return ans; } };
- LC 题目链接
-