520. Detect Capital

2021-05-05 12:27

阅读:724

标签:empty   题目   tcap   ase   public   asc   false   div   let   

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.

题目含义:给定一个词,你需要判断它中的资本的使用是否正确。当以下情况之一存在时,我们将单词中资本的使用定义为正确:这个单词中的所有字母都是大写,如“USA”。这个单词中的所有字母都不是大写,例如“leetcode”。只有此字中的第一个字母是大写,如果它有多个字母,如“Google”。否则,我们定义这个词不以正确的方式使用大写。

思路:找出所有大写字母的个数captialCount,与字符串长度做比较,都是小写字母、都是大写字母、只有首字母是大写字母的,都返回true。判断公式为:

captialCount == 0 || captialCount == word.length() || (captialCount == 1 && (‘Z‘ - word.charAt(0) >= 0))

 

字母    ASCII码      十进制数
0         00110000      48
9           00111001        57
A          01000001         65
Z          01011010         90
a         01100001         97
z          01111010         122
DEL (delete)   01111111   127

 

1     public boolean detectCapitalUse(String word) {
2         char[] words = word.toCharArray();
3         int captialCount = 0;
4         for (char letter : words) {
5             if (‘Z‘ - letter >= 0) captialCount++;
6         }
7 return captialCount == 0 || captialCount == word.length() || (captialCount == 1 && (‘Z‘ - word.charAt(0) >= 0)); 8 }

 

520. Detect Capital

标签:empty   题目   tcap   ase   public   asc   false   div   let   

原文地址:http://www.cnblogs.com/wzj4858/p/7680279.html


评论


亲,登录后才可以留言!