[LeetCode By Go 19]520. Detect Capital

写了这么多题,感觉用go写真方便,可以直接对解题的函数进行测试,测试代码写起来也好方便,多个测试用例很方便就放在一起,简单明了。

题目

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 if it has more than one letter, 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.

解题思路

判断大写是否正确,针对3种情况分别判断,如果有一项满足则返回true,都不满足返回false

  1. 将字符串全转为大写,和原字符串比较
  2. 将字符串全转为小写,和原字符串比较
  3. 将字符串第一个字符转为大写,和原字符串比较

代码

detectCapital.go

package _520_Detect_Capital

import "strings"

func DetectCapitalUse(word string) bool {
    //case 1
    upper := strings.ToUpper(word)
    if upper == word {
        return true
    } else {
        //case 2
        lower := strings.ToLower(word)
        if lower == word {
            return true
        }

        //case 3
        lowerRune := []rune(lower)
        wordRune := []rune(word)

        lowerRune[0] = lowerRune[0] + ('A' - 'a')
        lower2 := string(lowerRune)
        word2 := string(wordRune)
        if lower2 == word2 {
            return true
        }
    }

    return false
}

测试代码

detectCapital_test.go

package _520_Detect_Capital

import (
    "testing"
)

func TestDetectCapitalUse(t *testing.T) {
    var tests = []struct {
        input   string
        output bool
    }{
        {"USA", true},
        {"FlaG", false},
        {"Leetcode", true},
    }
    for _, test := range tests {
        ret := DetectCapitalUse(test.input)
        if ret == test.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", ret, test.output)
        }

    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/6832caea1b0f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞