Detect Capital

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:
All letters in this word are capitals, like "ABC".
All letters in this word are not capitals, like "abc".
Only the first letter in this word is capital, like "Abc".
Otherwise, we define that this word doesn't use capitals in the right way.

Example 1:

Input: "USA"
Output: True

Approach

Java

public class DetectCapital {
    public static void main(String[] args) {
        String str = "USA";
        System.out.println(detectCapitalUse(str));
    }

    static boolean detectCapitalUse(String word) {
        int n = word.length();
        if (n == 0)
            return true;
        int cnt = 0;
        for (int i = 0; i < n; i++)
            if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
                cnt++;
        if (cnt == 0 || cnt == n)
            return true;
        else {
            if (word.charAt(0) >= 'A' && word.charAt(0) <= 'Z') {
                for (int i = 1; i < n; i++)
                    if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
                        return false;
                return true;
            } else
                return false;
        }
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

bool detectCapitalUse(string word)
{
    int n = word.size();
    if (n == 0)
        return true;
    int cnt = 0;
    for (int i = 0i < ni++)
        if (word[i] >= 'A' && word[i] <= 'Z')
            cnt++;
    if (cnt == 0 || cnt == n)
        return true;
    else
    {
        if (word[0] >= 'A' && word[0] <= 'Z')
        {
            for (int i = 1i < ni++)
                if (word[i] >= 'A' && word[i] <= 'Z')
                    return false;
            return true;
        }
        else
            return false;
    }
}

int main()
{
    string str = "USA";
    if (detectCapitalUse(str))
        cout << "true";
    else
        cout << "false";
    return 0;
}


No comments:

Post a Comment