close

題目

  Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

  1. All letters in this word are capitals, like "USA".

  2. All letters in this word are not capitals, like "leetcode".

  3. Only the first letter in this word is capital if it has more than one letter, like "Google".

Otherwise, we define that this word doesn't use capitals in a right way.

Example 1:

Input: "USA"
Output: True

 

Example 2:

Input: "FlaG"
Output: False

想法

  首先判斷第一個字是大寫還是小寫,若是小寫,接下來都必須小寫才合法;若是大寫,有兩種情況,接下來都小寫就合法,或者是,接下來都大寫就合法。

利用小寫或大寫字母數量,與總共字母的數量來做判斷。

code

bool detectCapitalUse(char* word) {
    int i;
    int c=0, l=0, count=0;
    if(word[0]!=NULL){
        if(word[0]<'a'){
            for(i=1; word[i]!='\0'; i++){
                if(word[i]>='a'){
                    printf("%d\n", word[i]);
                    l++;
                }else{
                    c++;
                }
                count++;
            }
            if(c==count||l==count)
                return true;
            else
                return false;
        }else{
            for(i=1; word[i]!='\0'; i++){
                if(word[i]>='a'){
                    l++;
                }else{
                    c++;
                }
                count++;
            }
            if(l==count)
                return true;
            else
                return false;
        }
    }
    return;
}

 

arrow
arrow
    文章標籤
    LeetCode C string
    全站熱搜

    Davis 發表在 痞客邦 留言(0) 人氣()