blob: b4500919be446069b2d7e99fd497de9195f5f769 (
plain)
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
|
// 647. Palindromic Substrings
#include "leetcode.h"
/*
* given a string 's', return the number of palindromic substrings in it. a
* string is a palindrome when it reads the same backward as forward. a
* substring is a contiguous sequence of charcters within the string.
*/
int countSubstrings(char *s) {
int i = 0, num = 0, left = 0, right = 0;
while (s[i] != '\0') {
left = right = i;
while (left >= 0 && right < strlen(s) && s[left] == s[right]) {
num++;
left--;
right++;
}
left = i;
right = i + 1;
while (left >= 0 && right < strlen(s) && s[left] == s[right]) {
num++;
left--;
right++;
}
i++;
}
return num;
}
int main() {
char *s1 = "abc", *s2 = "aaa";
printf("%d\n", countSubstrings(s1)); // expect: 3
printf("%d\n", countSubstrings(s2)); // expect: 6
}
|