Go 練習問題
Palindrome Check in Go
Does the text read the same in both directions? Ignore spaces, punctuation and case.
学べること
- Filtering letters
- Lower case
- Comparing from both ends
level
l0
e1
v2
e3
l4
The same forwards and backwards
A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.
The first loop keeps only letters and digits in lower case. The second compares the first character with the last, the second with the second to last, and so on, and stops at the first difference. %q prints the text with quotes.
重要なポイント
- Keep only letters and digits.
- Compare in lower case.
- Stop at the first difference.
実行できる Go のサンプル
Go
main.go
package main
import (
"fmt"
"strings"
"unicode"
)
func isPalindrome(text string) bool {
letters := []rune{}
for _, r := range strings.ToLower(text) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
letters = append(letters, r)
}
}
for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 {
if letters[i] != letters[j] {
return false
}
}
return true
}
func main() {
for _, text := range []string{"level", "A man, a plan, a canal: Panama", "Go"} {
fmt.Printf("%q -> %t\n", text, isPalindrome(text))
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Go" -> false練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ