[Leetcode #520] Detect Capital

Seongyeol Shin·2022년 1월 24일
0

leetcode

목록 보기
139/196
post-thumbnail

Problem

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.

Idea

대문자를 사용하는 세 가지 규칙을 주어진 단어가 잘 지키고 있는지 확인하는 문제다.

우선 소문자가 사용되었는데 첫 번째 이후로 대문자가 나오면 곧바로 false를 리턴한다. 소문자가 나올 경우 소문자가 나왔다는 flag를 표시한다.

대문자의 개수를 세고, 마지막에 대문자의 수가 1이거나 작은지 확인한다. 이는 대문자가 첫번째에만 나온 경우를 허용하기 위함이다. 그리고 소문자를 포함하지 않을 때도 규칙을 지켰다고 판단한다. 이는 모든 문자가 대문자로 이뤄진 경우다.

Solution

class Solution {
    public boolean detectCapitalUse(String word) {
        boolean containsLowercase = false;
        int capitalCount = 0;

        for (int i=0; i < word.length(); i++) {
            if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z') {
                if (containsLowercase) {
                    return false;
                }
                capitalCount++;
            } else {
                containsLowercase = true;
            }
        }

        return capitalCount <= 1 || !containsLowercase;
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글