Skip to content
This repository was archived by the owner on May 5, 2025. It is now read-only.

Commit fc76ab5

Browse files
committed
adds C valid palindrome
1 parent dfc6c4b commit fc76ab5

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

C/strings/test_valid_palindrome.c

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#include <criterion/criterion.h>
2+
#include <stdbool.h>
3+
#include <ctype.h>
4+
#include <string.h>
5+
6+
/*
7+
Given a string s, determine if it is a palindrome, considering only
8+
alphanumeric characters and ignoring cases.
9+
Example 1:
10+
Input: s = "A man, a plan, a canal: Panama"
11+
Output: true
12+
Explanation: "amanaplanacanalpanama" is a palindrome.
13+
Example 2:
14+
Input: s = "race a car"
15+
Output: false
16+
Explanation: "raceacar" is not a palindrome.
17+
Constraints:
18+
1 <= s.length <= 2 * 105
19+
s consists only of printable ASCII characters.
20+
*/
21+
22+
bool
23+
is_palindrome(char * s)
24+
{
25+
bool alnum = false;
26+
int n = strlen(s);
27+
char simplified[n];
28+
int i, j = 0;
29+
for (i = 0; i < n; i++)
30+
{
31+
alnum = isalnum(s[i]);
32+
if (alnum)
33+
{
34+
simplified[j++] = tolower(s[i]);
35+
}
36+
}
37+
int new_n = j;
38+
i = 0;
39+
while (1)
40+
{
41+
if (i >= new_n)
42+
{
43+
return true;
44+
}
45+
if (simplified[i++] != simplified[j - i])
46+
{
47+
return false;
48+
}
49+
}
50+
}
51+
52+
Test(test_valid_palindrome, one_char_returns_true)
53+
{
54+
cr_assert(is_palindrome("G"));
55+
}
56+
57+
Test(test_valid_palindrome, panama_canal_returns_true)
58+
{
59+
cr_assert(is_palindrome("A man, a plan, a canal: Panama"));
60+
}
61+
62+
Test(test_valid_palindrome, salmon_returns_false)
63+
{
64+
cr_assert(!is_palindrome("SALMON"));
65+
}
66+
67+
Test(test_valid_palindrome, hannah_returns_true)
68+
{
69+
cr_assert(is_palindrome("Hannah"));
70+
}
71+
72+
Test(test_valid_palindrome, matrix_returns_false)
73+
{
74+
cr_assert(!is_palindrome("matrix"));
75+
}
76+
77+
Test(test_valid_palindrome, 90509_returns_true)
78+
{
79+
cr_assert(is_palindrome("90509"));
80+
}
81+
82+
Test(test_valid_palindrome, madam_im_adam_returns_true)
83+
{
84+
cr_assert(is_palindrome("Madam I'm Adam"));
85+
}
86+
87+
Test(test_valid_palindrome, greek_thing_returns_true)
88+
{
89+
cr_assert(is_palindrome("ΝΙΨΟΝ ΑΝΟΜΗΜΑΤΑ ΜΗ ΜΟΝΑΝ ΟΨΙΝ"));
90+
}
91+
92+
Test(test_valid_palindrome, mr_owl_returns_true)
93+
{
94+
cr_assert(is_palindrome("Mr. Owl ate my metal worm"));
95+
}
96+
97+
Test(test_valid_palindrome, mr_bowl_returns_false)
98+
{
99+
cr_assert(!is_palindrome("Mr. Bowl ate my metal worm"));
100+
}
101+

0 commit comments

Comments
 (0)