2021.11.13 - 148.检测大写字母

1. 题目

在这里插入图片描述

2. 思路

(1) 模拟法

  • 分别讨论三种情况即可。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public boolean detectCapitalUse(String word) {
    
    
        int n = word.length();
        if (n < 2) {
    
    
            return true;
        }
        if (isUpperCase(word.charAt(0))) {
    
    
            if (isUpperCase(word.charAt(1))) {
    
    
                for (int i = 2; i < n; i++) {
    
    
                    if (!isUpperCase(word.charAt(i))) {
    
    
                        return false;
                    }
                }
            } else {
    
    
                for (int i = 2; i < n; i++) {
    
    
                    if (isUpperCase(word.charAt(i))) {
    
    
                        return false;
                    }
                }
            }
        } else {
    
    
            for (int i = 1; i < n; i++) {
    
    
                if (isUpperCase(word.charAt(i))) {
    
    
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isUpperCase(char ch) {
    
    
        return ch >= 65 && ch <= 90;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121303711