520. Detect Capital判断单词有效性

[抄题]:

Given a word, you need to judge whether the usage of capitals in it is right or not.

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

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. Only the first letter in this word is capital if it has more than one letter, like "Google".

Otherwise, we define that this word doesn't use capitals in a right way.

 

Example 1:

Input: "USA"
Output: True

 

Example 2:

Input: "FlaG"
Output: False

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么表示大写字母:c <= 'Z'

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

c <= 'Z'

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

charAt 可以把字符串中的字母单独抽出来

[关键模板化代码]:

统计大写字母:

for (char c : word.toCharArray()) {
            if (c <= 'Z') count++;
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public boolean detectCapitalUse(String word) {
        //ini
        int count = 0;
        for (char c : word.toCharArray()) {
            if (c <= 'Z') count++;
        }
        if (count == 0 || count == word.length() || (count == 1 && word.charAt(0) <= 'Z')) {
            return true;
        }
        return false;
    }
}
View Code

 

posted @ 2018-03-24 22:30  苗妙苗  阅读(113)  评论(0编辑  收藏  举报