본문 바로가기
Algorithm/LeetCode

LeetCode - Detect Capital

by HaningYa 2020. 8. 7.
728x90

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


문제

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 {
    func detectCapitalUse(_ word: String) -> Bool {
        // all letter in capital
        if word == word.uppercased(){
            return true
        }
        
        //all letter are not capital
        if word == word.lowercased(){
            return true
        }
        //first letter capital
        if String(word.first!) == String(word.first!).uppercased(){
            var tmp = word
            tmp.removeFirst()
            if tmp == tmp.lowercased(){
                return true
            }
        }
        return false   
    }
}
728x90

댓글