알고리즘/해결

LeetCode August1.Detect Capital

언클린 2020. 8. 3. 11:07
728x90

1. 문제(원본)

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.

2. 문제

단어의 대소문자 쓰임에 대하여 알고리즘을 작성하라

3. 나의 답

class Solution {

    func detectCapitalUse(_ word: String) -> Bool {

        guard let isfirstCharUpper = word.first?.isUppercase else {

            print("error Data!")

            return false

        }

        var flag = 0

        word.forEach { (c) in

            if c.isUppercase {

                flag += 1

            } else if c.isLowercase {

                flag -= 1

            }

        }

        return isfirstCharUpper ?

            (flag == word.count) || (flag == -(word.count - 2))

            : (flag == -(word.count))

    }

}

4. 다른 유저의 답

#1

class Solution {

    func detectCapitalUse(_ word: String) -> Bool {

        return word.contains { !$0.isUppercase } == false

        || word.dropFirst().contains { $0.isUppercase } == false

    }

}

5. 마무리

이번 문제에 있어서는 처음에 isUppercase의 존재를 몰라 직접 아스키코드를 사용해서 isUppercase 같은 함수도 같이 만들어 실행했었는데 막상 작성하고 나니 발견되어 수정하게 되었다. 문제 풀 당시 처음에 앞에 대문자만 생각하면 되는 줄 알고 플래그의 수를 계산하여 답을 산출하는 방식으로 진행하였는데 중간에도 대문자가 있으면 같은 결과가 나온다는 것을 알고 앞부분만 생각하면 안 된다는 것을 알았다.

문제는 풀렸지만 다른 유저의 답변을 보았을 때는 진짜 와 저런 방법이... 하는 생각이 드는 답변이 있었다. contains의 활용이었는데 진짜 간단하게 풀려버렸다. 이번 문제는 한 줄 코딩은 안 되겠지라고 생각했는데 역시 방법은 있구나 하는 생각이 들었다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

[프로그래머스] 없는 숫자 더하기  (0) 2021.12.08
LeetCode August2.Design HashSet  (0) 2020.08.03
LeetCode1528. Shuffle String  (0) 2020.07.30
LeetCode1480. Running Sum of 1d Array  (0) 2020.07.30
LeetCode1470. Shuffle the Array  (0) 2020.07.28