C++ easy to understand solution (runs in 6 ms)


  • 0
    K

    Here is my solution. I hope it is fairly readable and self explanatory. There is an opportunity for early return when both flags are set to false, but I think that checking that is not worth the effort. What do you think?

    bool detectCapitalUse(string word){
            bool all_lower = true, all_upper = true;  
          
            if (word.size() <= 1) return true;    
        
            for(int ii = 1; ii < word.size(); ++ii)
            {
                if(islower(word[ii]))  
                    all_upper = false;                     
                else 
                    all_lower = false;
            }
            return all_lower || (all_upper && isupper(word[0]));               
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.