layout: posttitle: PHP 实现检测大写字母
subtitle: PHP 实现检测大写字母
date: 2020-05-22
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 检测大写字母

检测大写字母

给定一个单词,你需要判断单词的大写使用是否正确。

我们定义,在以下情况时,单词的大写用法是正确的:

  1. 全部字母都是大写,比如”USA”。
  2. 单词中所有字母都不是大写,比如”leetcode”。
  3. 如果单词不只含有一个字母,只有首字母大写, 比如 “Google”。

否则,我们定义这个单词没有正确使用大写字母。

示例 1:

  1. 输入: "USA"
  2. 输出: True

示例 2:

  1. 输入: "FlaG"
  2. 输出: False

注意: 输入是由大写和小写拉丁字母组成的非空单词。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/detect-capital

解题思路

倒序字符串,从后往前开始判断,相邻两个字母大小写不一致的话,必然是不合法的。
特殊处理第一第二个字母,如果两个大小写不一致同时第二位是大写的话,一定是不合法的。

PHP 实现

  1. class Solution {
  2. /**
  3. * @param String $word
  4. * @return Boolean
  5. */
  6. function detectCapitalUse($word) {
  7. $length = strlen($word);
  8. for ($i = $length - 1; $i > 0; $i--) {
  9. // 相邻两个大小写不一致一定不合法
  10. if (checkCase($word[$i]) !== checkCase($word[$i - 1]) && $i >= 2) {
  11. return false;
  12. }
  13. // 特殊处理第一二个字母的大小写判断
  14. if ($i === 1 && checkCase($word[$i]) !== checkCase($word[$i - 1]) && checkCase($word[$i]) === 1) {
  15. return false;
  16. }
  17. }
  18. return true;
  19. }
  20. }
  21. function checkCase($letter)
  22. {
  23. return $letter === strtoupper($letter) ? 1 : 0;
  24. }

© 原创文章

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券