您好,欢迎访问一九零五行业门户网

Leetcode PHP题解--D81 520. Detect Capital

d81 520. detect capital
题目链接
520. detect capital
题目分析
给定一个单词,判断其使用大写的方式正确与否。
思路
如果给定单词是全大写或全小写的话,属于正确用法。
用array_count_values的结果和包含全大写或全小写的数组计算差集,结果为空集则说明为全大写或全小写。直接返回true即可。
除了全大写和全小写的情况外,只能出现首字母大写,其余字母小写的情况。
故我们把第一个字符排除掉,再判断剩余字母是否为全小写。判断方法与前面相同。(php视频教程)
最终代码
<?phpclass 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的详细内容。
其它类似信息

推荐信息