写了这么多题,感觉用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:
- 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.
解题思路
判断大写是否正确,针对3种情况分别判断,如果有一项满足则返回true,都不满足返回false
- 将字符串全转为大写,和原字符串比较
- 将字符串全转为小写,和原字符串比较
- 将字符串第一个字符转为大写,和原字符串比较
代码
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)
}
}
}