This repository has been archived by the owner on Dec 13, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path17-recursion_palindrome.zig
67 lines (61 loc) · 1.68 KB
/
17-recursion_palindrome.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const std = @import("std");
/// Function to check if a string is a palindrome recursively.
///
/// # Parameters
///
/// - `str`: The string to check.
/// - `left`: The left index for comparison.
/// - `right`: The right index for comparison.
///
/// # Returns
///
/// `true` if the string is a palindrome, `false` otherwise.
fn isPalindromeRecursive(str: []const u8, left: usize, right: usize) bool {
// Base case: If left index is greater or equal to right, all characters have been checked
if (left >= right) {
return true;
}
// If characters at current indices do not match, it's not a palindrome
if (str[left] != str[right]) {
return false;
}
// Move towards the center
return isPalindromeRecursive(str, left + 1, right - 1);
}
/// Helper function to check if a string is a palindrome.
///
/// # Parameters
///
/// - `str`: The string to check.
///
/// # Returns
///
/// `true` if the string is a palindrome, `false` otherwise.
fn isPalindrome(str: []const u8) bool {
if (str.len == 0) {
return true;
}
return isPalindromeRecursive(str, 0, str.len - 1);
}
/// Main function to demonstrate the palindrome checker.
pub fn main() !void {
const test_strings = [_][]const u8{
"radar",
"level",
"hello",
"racecar",
"madam",
"step on no pets",
"",
"abcba",
"not a palindrome",
};
for (test_strings) |str| {
std.debug.print("Testing: \"{s}\"\n", .{str});
if (isPalindrome(str)) {
std.debug.print("Result: It's a palindrome.\n\n", .{});
} else {
std.debug.print("Result: It's not a palindrome.\n\n", .{});
}
}
}