C++ Solution


  • 7
    Z
    class Solution {
    public:
        bool detectCapitalUse(string word) {
    		int size=word.size(),count=0;
    		if(size<=1)
    			return true;
    		for (int i = 1; i < size; i++){
    			if(word[i]>='a'&&word[i]<='z')
    				count+=1;
    			else
    				count+=2;
    		}
    		if(count==size-1)
    			return true;
    		else if(count==2*(size-1))
    			return word[0]>='A'&&word[0]<='Z';
    		else 
    			return false;
        }
    };
    

    From 1~size-1,if we meet with a-z,we add 1,else we add 2.Then we can get the result that if the second to last letter is all lowercase or all upcase.


  • 0
    W

    thinks for your method, it worked well.


  • 0
    A
    bool detectCapitalUse(string word) {
        const char *c = word.c_str();
        if (word.size() <= 1) return true;
        if (*c <= 'z' && *c >= 'a') {
            c = c + 1;
            while (*c) {
                if (*c <= 'Z' && *c >= 'A') return false;
                c = c + 1;
            }
        } else {
            c = c + 1;
            if (*c <= 'Z' && *c >= 'A') {
                c = c + 1;
                while (*c) {
                    if (*c <= 'z' && *c >= 'a') return false;
                    c = c + 1;
                }
            } else {
                c = c + 1;
                while (*c) {
                    if (*c <= 'Z' && *c >= 'A') return false;
                    c = c + 1;
                }
            }
        }
            
        return true;
    }
    

    not use the counter, maybe complex.


Log in to reply
 

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