Упражнения по Go

Palindrome Check in Go

Does the text read the same in both directions? Ignore spaces, punctuation and case.

  • Начальный
  • Чтение: 3 мин
  • Примеров для запуска: 1
Что вы узнаете
  • Filtering letters
  • Lower case
  • Comparing from both ends
level
l0
e1
v2
e3
l4
The first and last letters match, then the next pair.

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.

Главное

  1. Keep only letters and digits.
  2. Compare in lower case.
  3. 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

Практика

Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.

Закончили этот урок?

Отметьте его как изученный, чтобы следить за прогрессом.

Далее: Word Frequency Counter →

Попрактикуйтесь на задаче

Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.

Все задачи