Palindrome check a string

PHPz
Release: 2024-07-17 13:36:15
Original
1207 people have browsed it

Palindrome check a string

This one is pretty common. Sounds difficult, but not really bad once you think it through.

Write a golang function to check if a string is a palindrome.

A palindrome is a sequence of characters that is the same even when reversed, for example:

  • "aba" is a palindrome

  • "abb is not

  • "ab a" is considered a palindrome by most, so we ignore whitespace.

func PalindromeCheck(str string) bool {
    trimmedStr := strings.ReplaceAll(str, " ", "")
    len := len(trimmedStr)
    chars := []rune(trimmedStr)
    for i := 0; i < len/2; i++ {
        if chars[i] != chars[len-i-1] {
            return false
        }
    }
    return true
}
Copy after login

This solution is functionally the same as you will find for C or Java when searching online. We are essentially using dual pointers to traverse from the beginning and the end looking for a mismatched character. When a mismatch is found, we can declare the string is not a palindrome.

Can we make it better?
Is there a better way to trim whitespace rather than using strings.ReplaceAll? (there is but it can get ugly)
What about the efficiency of converting to an []rune, is there a better way?

Post your thoughts in the comments.

Thanks!

The code for this post and all posts in this series can be found here

The above is the detailed content of Palindrome check a string. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template