leetcode每日一题-520:检测大写字母
链接
检测大写字母
题目
分析
模拟分析题,遍历一下字符串统计一下其中的大小写字母然后根据大小写字母的数量判断即可
代码
C++
class Solution {
public:
bool detectCapitalUse(string word) {
int n = word.size();
// 统计大写,小写字母的数量
int big = 0, little = 0;
for(int i=0 ; i<n ; i++)
{
// 这里使用if-else if是为了避免其他字符的干扰
if(word[i] >= 'a' and word[i] <= 'z') little++;
else if(word[i] >= 'A' and word[i] <= 'Z') big++;
}#
// 如果字符串都是大写or小写字母,显然符合 return 1
if(big == n or little == n) return 1;
// 如果大小写的数量之和等于字符串总数,并且只有一个大写字母,且这个大写字母是第一个字符,那么return 1
if((big + little == n) and big == 1 and word[0] >= 'A' and word[0] <= 'Z') return 1;
// 不符合上述情况的就不合法,return 0即可
return 0;
}
};
Java
class Solution {
public boolean detectCapitalUse(String word) {
// 若第 1 个字母为小写,则需额外判断第 2 个字母是否为小写
if (word.length() >= 2 && Character.isLowerCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
return false;
}
// 无论第 1 个字母是否大写,其他字母必须与第 2 个字母的大小写相同
for (int i = 2; i < word.length(); ++i) {
if (Character.isLowerCase(word.charAt(i)) ^ Character.isLowerCase(word.charAt(1))) {
return false;
}
}
return true;
}
}
作者:LeetCode-Solution