LeetCode 520 Detect Capital

题意

给与一个单词,判断其大写字母的使用是否正确,即每个字母都是大写或都是小写,或首字母大写。

Example 1:

1
2
Input: "USA"
Output: True

Example 2:

1
2
Input: "FlaG"
Output: False

解法

定义两个变量,记录小写字母个数和大写字母个数,然后判断条件是否符合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public boolean detectCapitalUse(String word) {
if (word.length() < 2) {
return true;
}
char[] chars = word.toCharArray();
int lower = 0, upper = 0;
for (int i = 0; i < chars.length; i++) {
if (isLowerCaseLetter(chars[i])) {
lower++;
} else {
upper++;
}
}

return lower == chars.length || upper == chars.length ||
(isUpperCaseLetter(chars[0]) && lower == chars.length - 1);
}

public boolean isUpperCaseLetter(char c) {
return c >= 65 && c <= 90;
}

public boolean isLowerCaseLetter(char c) {
return c >= 97 && c <= 122;
}
}

Runtime: 12 ms, faster than 98.36% of Java online submissions for Detect Capital.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-520/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!