C++ solution, checking from the back with early exit


  • 0
    H
    class Solution {
    public:
        bool detectCapitalUse(string word) {
        	// if the last character is capital
            if( *(word.end()-1) <= 'Z' ) {
            	// then all characters must be capital
            	for(auto itr = word.end()-2; itr >= word.begin(); --itr)
            		if(*itr >= 'a') return false;
            	
            	return true;
            }
            // if the last character is in lowercase
            else {
            	// then all characters but the first must be in lowercase
            	for(auto itr = word.end()-2; itr > word.begin(); --itr)
            		if(*itr <= 'Z') return false;
            	
            	return true;
            }
        }
    };
    

Log in to reply
 

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