好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

LeetcodePHP题解--D81520.DetectCapital

D81 520. Detect Capital

题目链接

520. Detect Capital

题目分析

给定一个单词,判断其使用大写的方式正确与否。

思路

如果给定单词是全大写或全小写的话,属于正确用法。
用array_count_values的结果和包含全大写或全小写的数组计算差集,结果为空集则说明为全大写或全小写。直接返回true即可。

除了全大写和全小写的情况外,只能出现首字母大写,其余字母小写的情况。
故我们把第一个字符排除掉,再判断剩余字母是否为全小写。判断方法与前面相同。(php视频教程)

最终代码

<?php
class Solution {    /**
* @param String $word
* @return Boolean
*/
    function detectCapitalUse($word) {
   $wordArray = str_split($word);
   $uppercase = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
   $lowercase = str_split('abcdefghijklmnopqrstuvwxyz');  
   //all upper or lower case
   if(!array_diff_key(array_count_values($wordArray),array_flip($uppercase))
 ||!array_diff_key(array_count_values($wordArray),array_flip($lowercase))){  return true;
   }   //first letter whatever case,
   //rest of the string must be all lowercase
   array_shift($wordArray);   if(!array_diff_key(array_count_values($wordArray),array_flip($lowercase))){ return true; 
   }   return false;
    }
}

以上就是Leetcode PHP题解--D81 520. Detect Capital的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于LeetcodePHP题解--D81520.DetectCapital的详细内容...

  阅读:49次