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; iThis 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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3