D81 520. Detect Capital
Question link
Question analysis
Given a word, determine whether its capitalization is correct or not.
Ideas
If a given word is in all uppercase or all lowercase, it is a correct usage.
Use the result of array_count_values and the array containing all uppercase or all lowercase to calculate the difference set. If the result is an empty set, it means all uppercase or all lowercase. Just return true directly.
Except for all uppercase and all lowercase, only the first letter can be capitalized and the remaining letters are lowercase.
So we exclude the first character and then determine whether the remaining letters are all lowercase. The judgment method is the same as before. (php video tutorial)
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; } }
The above is the detailed content of Leetcode PHP题解--D81 520. Detect Capital. For more information, please follow other related articles on the PHP Chinese website!