본문 바로가기
📁 코딩테스트 준비/C++

[LeetCode] August 1st. Detect Capital

by 박개봄 2020. 8. 3.
728x90

문제

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, 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

 

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

 

 

구현 코드

class Solution {
public:
    bool detectCapitalUse(string word) {
        
        bool ans=true;
        
        if(word[0]>=97&&word[0]<=122){ //0번째 문자가 소문자인 경우
            for(int i=0;i<word.length();i++){
                if(word[i+1]>=65 && word[i+1]<=90){
                    ans = false;
                }
            }
        }
        
        else if(word[0]>=65&&word[0]<=90){ //0번째 문자가 대문자인 경우
            for(int i=0;i<word.length();i++){
                if(word[i+1]>=65&&word[i+1]<=90){
                    if(word[i+2]>=97&&word[i+2]<=122){
                        ans=false;
                    }
                }
                
                else if(word[i+1]>=97&&word[i+1]<=122){
                    if(word[i+2]>=65&&word[i+2]<=90){
                        ans=false;
                    }
                }
            }
        }
        
       return ans;
    }
};

언어는 c++

728x90