Skip to content
Middle+65 views

Напишите функцию на Go, которая проверяет, является ли заданная строка палиндромом. Функция должна игнорировать регистр и пробелы. Кроме того, специальные символы также должны игнорироваться. Например, строка "A man, a plan, a canal: Panama" должна считаться палиндромом.

Practice

Asked at

AI answer

You can keep only letters and digits, convert them to lowercase, and compare the resulting sequence with its reverse. unicode allows you to correctly handle more than just ASCII. In Go, range over a string and []rune work with Unicode code points.

func IsPalindrome(s string) bool {
    runes := make([]rune, 0, len(s))
    for _, r := range s {
        if unicode.IsLetter(r) || unicode.IsDigit(r) {
            runes = append(runes, unicode.ToLower(r))
        }
    }

    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        if runes[i] != runes[j] {
            return false
        }
    }
    return true
}

Add the unicode import. In this implementation, spaces, punctuation, and other characters are ignored; an empty string is considered a palindrome.

Also asked at Астон

Similar questions