Last active
April 3, 2023 12:50
-
-
Save kahunacohen/8e94b789c8e30e1ccabf993eac0478cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// A recursive palindrome function. The terminal cases | |
// are: | |
// A. when a string is less than or equal to 1 (a 1 length string is by | |
// definition a palindrome). | |
// B. when the first and last characters of a string don't match, we know | |
// the whole string is not a palindrome. | |
func isPalindromeRecursive(s string) bool { | |
// Terminal conditions: | |
// string is length 1: return true | |
// first and last are not equal: return false | |
if len(s) <= 1 { | |
return true | |
} | |
firstChar := s[0] | |
lastChar := s[len(s)-1] | |
if firstChar != lastChar { | |
return false | |
} | |
// Get 0 to second to last (chop off last) | |
// since, last part of slice notation is exclusive. | |
sliced := s[:len(s)-1] | |
// Take the result and chop off the first element. | |
sliced = sliced[1:] | |
return isPalindromeRecur(sliced) | |
} | |
func main() { | |
fmt.Println(isPalindromeRecursive("racecar")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment