Skip to content

Commit b46d6da

Browse files
authored
Add recursive method for palindrome (TheAlgorithms#455)
1 parent 75b615c commit b46d6da

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

strings/palindrome/ispalindrome.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,21 @@ func IsPalindrome(text string) bool {
3535
}
3636
return true
3737
}
38+
39+
func IsPalindromeRecursive(text string) bool {
40+
clean_text := cleanString(text)
41+
runes := []rune(clean_text)
42+
return isPalindromeRecursiveHelper(runes, 0, int64(len(runes)))
43+
}
44+
45+
func isPalindromeRecursiveHelper(runes []rune, start int64, end int64) bool {
46+
if start >= end {
47+
return true
48+
}
49+
if runes[start] != runes[end-1] {
50+
return false
51+
}
52+
start = start + 1
53+
end = end - 1
54+
return isPalindromeRecursiveHelper(runes, start, end)
55+
}

strings/palindrome/ispalindrome_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,14 @@ func TestIsPalindrome(t *testing.T) {
5151
})
5252
}
5353
}
54+
55+
func TestIsPalindromeRecursive(t *testing.T) {
56+
for _, test := range testCases {
57+
t.Run(test.name, func(t *testing.T) {
58+
func_result := IsPalindromeRecursive(test.input)
59+
if test.expected != func_result {
60+
t.Errorf("Expected answer '%t' for string '%s' but answer given was %t", test.expected, test.input, func_result)
61+
}
62+
})
63+
}
64+
}

0 commit comments

Comments
 (0)