본문 바로가기
Computer Science/알고리즘

leetcode 520) Detect Capital

by eeeun:) 2022. 1. 25.
반응형

LV. Easy 😎

https://leetcode.com/problems/detect-capital/

 

Detect Capital - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

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 "USA".
  • All letters in this word are not capitals, like "leetcode".
  • Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

 

Example 1:

Input: word = "USA"
Output: true

Example 2:

Input: word = "FlaG"
Output: false

 

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

 

문제 해결법

true를 리턴하는 3가지 경우를 체크해줬다.

flag를 두어 3가지 경우 중 word가 몇 번째 경우인지를 저장해 true인지 false인지 체크했다.

 

해결 코드
class Solution {
public:
    bool detectCapitalUse(string word) {
        // 0 : all capital, 1 : not all capital, 2 : first = capital
        int flag = word[0] >= 65 && word[0] <= 90 ? 0 : 1;
        for (int i = 1; i < word.size(); ++i) {
           if (flag == 0) {
               if (!(word[i] >= 65 && word[i] <= 90)) {
                   if (i == 1)
                       flag = 2;
                   else
                       return false;
               }
           }
            else {
                if (word[i] >= 65 && word[i] <= 90)
                    return false;
            }
        }
        return true;
    }
};

728x90

댓글