의역:

대문자 사용을 다음과 같이 정의할 때 다음 조건들을 모두 만족하면 true 아니면 false를 반환해라

  • 모든 문자가 대문자여야 한다. ex: "USA"
  • 모든 문자는 소문자여야 한다. ex: "leetcode"
  • 첫 번째 글자만 대문자이고 나머지는 소문자여야 한다. ex: "Google" 

풀이: 

1. 각각의 경우를 따로 분리하여 체크하고 취합

class Solution {
    public boolean upperCheck(String word){
        for(int i=0;i<word.length();i++){
            //Character.isUpperCase()로 대체 가능
            if('A'>word.charAt(i)||'Z'<word.charAt(i))
                return false;
        }
        return true;
    }
    public boolean lowerCheck(String word){
        //Character.isLowerCase()로 대체 가능
        for(int i=0;i<word.length();i++){
            if('a'>word.charAt(i)||'z'<word.charAt(i))
                return false;
        }
        return true;
    }
    public boolean firstCheck(String word){
        //Character.isUpperCase()로 대체 가능
        if('A'>word.charAt(0)||'Z'<word.charAt(0))
            return false;
        for(int i=1;i<word.length();i++){
            //Character.isLowerCase()로 대체 가능
            if('a'>word.charAt(i)||'z'<word.charAt(i))
                return false;
        }
        return true;
    }
    public boolean detectCapitalUse(String word) {
        //시간복잡도 O(n), 공간복잡도 O(1)
        return upperCheck(word)||lowerCheck(word)||firstCheck(word);
    }
}

 

2. 정규식 사용 (패턴 매칭에는 해당 방법이 유용하지만 상대적으로 시간이 오래걸린 다는 단점이 존재) 

String.matches(String regex) 함수는 이 문자열이 인수로 넣은 정규식과 일치하는지 여부를 나타냅니다.

[A-Z] 은 A~Z 까지의 문자 중에서 하나의 문자와 일치하는 패턴을 말하며
뒤에 *가 붙게되면 0회 이상 반복하는 것을 말합니다. 따라서 [A-Z]* -> 대문자로만 이루어진 문자열

class Solution {
    public boolean detectCapitalUse2(String word) {
        //시간복잡도 O(word.matches()), 공간복잡도 O(1)
        // 1. "ABC" 는 [A-Z]* 으로 걸러내는 것이 가능
        // 2. "abc" 는 [a-z]* 으로 걸러내는 것이 가능
        // 3. "Abc" 는 [A-Z][a-z]* 으로 걸러내는 것이 가능
        // 1+2+3을 | or 연산자로 합침
        return word.matches("[A-Z]*|[a-z]*|[A-Z][a-z]*");
    }
}

 

3. 파이썬의 Built in(내장) 함수 사용

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
    #공간복잡도 O(1) 시간복잡도는 Built-in 함수 만큼.. 
        return word.isupper() or word.islower() or word.istitle()

링크: https://leetcode.com/problems/detect-capital/description/

+ Recent posts