寫了這么多題,感覺用go寫真方便,可以直接對(duì)解題的函數(shù)進(jìn)行測(cè)試,測(cè)試代碼寫起來也好方便,多個(gè)測(cè)試用例很方便就放在一起,簡(jiǎn)單明了。
題目
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:
- 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 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.
解題思路
判斷大寫是否正確,針對(duì)3種情況分別判斷,如果有一項(xiàng)滿足則返回true,都不滿足返回false
- 將字符串全轉(zhuǎn)為大寫,和原字符串比較
- 將字符串全轉(zhuǎn)為小寫,和原字符串比較
- 將字符串第一個(gè)字符轉(zhuǎn)為大寫,和原字符串比較
代碼
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
}
測(cè)試代碼
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)
}
}
}