Home  >  Article  >  Backend Development  >  Leetcode PHP题解--D81 520. Detect Capital

Leetcode PHP题解--D81 520. Detect Capital

步履不停
步履不停Original
2019-06-10 09:38:561926browse

Leetcode PHP题解--D81 520. Detect Capital

D81 520. Detect Capital

Question link

520. Detect Capital

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(&#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;);
        $lowercase = str_split(&#39;abcdefghijklmnopqrstuvwxyz&#39;);       
        //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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn