LeetCode - Easy - 520. Detect Capital

柔情只为你懂 2022-10-15 04:44 241阅读 0赞

Topic

  • String

Description

https://leetcode.com/problems/detect-capital/

We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA".
  • All letters in this word are not capitals, like "leetcode".
  • Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

Example 1:

  1. Input: word = "USA"
  2. Output: true

Example 2:

  1. Input: word = "FlaG"
  2. Output: false

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

Analysis

方法一:字符统计

方法二:正则表达式

Submission

  1. public class DetectCapital {
  2. public boolean detectCapitalUse(String word) {
  3. int capitalCount = 0, notCapitalCount = 0;
  4. boolean firstLetterCapital = Character.isUpperCase(word.charAt(0));
  5. for(int i = 0; i < word.length(); i++) {
  6. if(Character.isUpperCase(word.charAt(i))) {
  7. capitalCount++;
  8. }else {
  9. notCapitalCount++;
  10. }
  11. }
  12. return firstLetterCapital && notCapitalCount == word.length() - 1 //
  13. || notCapitalCount == word.length()//
  14. || capitalCount == word.length();
  15. }
  16. public boolean detectCapitalUse2(String word) {
  17. return word.matches("[A-Z]*|[A-Z]?[a-z]*");
  18. }
  19. }

Test

  1. public class DetectCapitalTest {
  2. @Test
  3. public void test() {
  4. DetectCapital obj = new DetectCapital();
  5. assertTrue(obj.detectCapitalUse("USA"));
  6. assertTrue(obj.detectCapitalUse("leetcode"));
  7. assertTrue(obj.detectCapitalUse("Google"));
  8. assertTrue(obj.detectCapitalUse("g"));
  9. assertFalse(obj.detectCapitalUse("FlaG"));
  10. assertTrue(obj.detectCapitalUse2("USA"));
  11. assertTrue(obj.detectCapitalUse2("leetcode"));
  12. assertTrue(obj.detectCapitalUse2("Google"));
  13. assertTrue(obj.detectCapitalUse2("g"));
  14. assertFalse(obj.detectCapitalUse2("FlaG"));
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode520. 检测大写字母

    给定一个单词,你需要判断单词的大写使用是否正确。 我们定义,在以下情况时,单词的大写用法是正确的: 1. 全部字母都是大写,比如"USA"。 2. 单词中所有字母都不是