D81 520. Detect Capital
Topic Link
Topic analysis
Given a word, the way to judge its uppercase is correct or not.
Thinking
If a given word is all uppercase or lowercase, it belongs to the correct usage.
Calculating a difference with the set array contains the results array_count_values and all uppercase or lowercase, and then the result is the empty set is all uppercase or lowercase. Returns true to direct.
In addition to all uppercase and lowercase the whole situation, and the rest lowercase situation can only occur capitalized.
Therefore, we exclude the first character, and then determine whether the remaining letters to lowercase. The method of determining the same as before.
The final code
<?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;
}
}
If you find this article useful, welcomed with love of power assistance.
Reproduced in: https: //www.jianshu.com/p/b92d244f924c