LeetCode之Detect Capital

举报
chenyu 发表于 2021/07/27 00:11:47 2021/07/27
【摘要】 1、题目   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 hol...

1、题目

 

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:


  
  1. Input: "USA"
  2. Output: True

Example 2:


  
  1. Input: "FlaG"
  2. Output: False

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

Subscribe to see which companies asked this question.

 

 

 

 

2、代码实现

 


  
  1. public class Solution {
  2. public boolean detectCapitalUse(String word) {
  3. if (word == null || word.length() == 0)
  4. return false;
  5. if (word.length() == 1)
  6. return true;
  7. int length = word.length();
  8. if (word.charAt(0) >= 65 && word.charAt(0) <= 90) {
  9. //AA**
  10. if (word.charAt(1) >= 65 && word.charAt(1) <= 90) {
  11. if (length > 2) {
  12. //AA*a*
  13. for (int i = 2 ; i < length; ++i) {
  14. if (word.charAt(i) >= 97 && word.charAt(i) <= 122)
  15. return false;
  16. }
  17. //AAA
  18. return true;
  19. } else {
  20. //AA
  21. return true;
  22. }
  23. }
  24. //Aa**
  25. if (word.charAt(1) >= 97 && word.charAt(1) <= 122) {
  26. if (length > 2) {
  27. for (int i = 2 ; i < length; ++i) {
  28. //Aa*A*
  29. if (word.charAt(i) >= 65 && word.charAt(i) <= 90)
  30. return false;
  31. }
  32. //Aaa
  33. return true;
  34. } else {
  35. //Aa
  36. return true;
  37. }
  38. }
  39. } else {
  40. //aAa
  41. for (int i = 1; i < length; i++) {
  42. if (word.charAt(i) >= 65 && word.charAt(i) <= 90)
  43. return false;
  44. }
  45. //aaa
  46. return true;
  47. }
  48. return false;
  49. }
  50. }

 

 

 

 

 

 

 

 

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/69654563

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。