|
| 1 | +// Source : https://leetcode.com/problems/detect-capital/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-02-04 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * |
| 8 | + * Given a word, you need to judge whether the usage of capitals in it is right or not. |
| 9 | + * |
| 10 | + * We define the usage of capitals in a word to be right when one of the following cases holds: |
| 11 | + * |
| 12 | + * All letters in this word are capitals, like "USA". |
| 13 | + * All letters in this word are not capitals, like "leetcode". |
| 14 | + * Only the first letter in this word is capital if it has more than one letter, like "Google". |
| 15 | + * |
| 16 | + * Otherwise, we define that this word doesn't use capitals in a right way. |
| 17 | + * |
| 18 | + * Example 1: |
| 19 | + * |
| 20 | + * Input: "USA" |
| 21 | + * Output: True |
| 22 | + * |
| 23 | + * Example 2: |
| 24 | + * |
| 25 | + * Input: "FlaG" |
| 26 | + * Output: False |
| 27 | + * |
| 28 | + * Note: |
| 29 | + * The input will be a non-empty word consisting of uppercase and lowercase latin letters. |
| 30 | + ******************************************************************************************************/ |
| 31 | +class Solution { |
| 32 | + bool is_lower(char ch) { |
| 33 | + return ch >='a' && ch <='z'; |
| 34 | + } |
| 35 | + bool is_upper(char ch) { |
| 36 | + return ch >='A' && ch <='Z'; |
| 37 | + } |
| 38 | + bool is_alpha(char ch) { |
| 39 | + return is_lower(ch) || is_upper(ch); |
| 40 | + } |
| 41 | +public: |
| 42 | + bool detectCapitalUse(string word) { |
| 43 | + bool all_upper = true, all_lower = true, first = is_upper(word[0]); |
| 44 | + for(int i=1; i<word.size(); i++) { |
| 45 | + if (is_lower(word[i])) all_upper = false; |
| 46 | + if (is_upper(word[i])) all_lower = false; |
| 47 | + } |
| 48 | + return all_lower || first && all_upper; |
| 49 | + } |
| 50 | +}; |
0 commit comments