Detect Capital(leetcode)

来源:互联网 发布:c语言定义结构体数组 编辑:程序博客网 时间:2024/05/21 09:17

Detect Capital

  • Detect Capital
    • 题目
    • 解决


题目

leetcode题目

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

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.


解决

class Solution {public:    bool detectCapitalUse(string word) {        int len = word.length();        int upper = 0;        int lower = 0;        for (int i = 0; i < len; i++) {            if (word[i] >= 'A' && word[i] <= 'Z') {                // word首字母大写或word中到目前为止都是大写字母                if (i == 0 || lower == 0) {                    upper++;                } else {                    return false;                }            } else if (word[i] >= 'a' && word[i] <= 'z') {                lower++;                if (upper > 1) {                    return false;                }            }        }        return true;    }};