blob: a5d2d52a2f7502eb2aa28c3699ee0c4be405a700 (
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
36
37
38
|
// 459. Repeated Substring Pattern
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/*
* given a string 's', check if it can be constructed by taking a substring of
* it and appending multiple copies of the substring together.
*/
bool repeatedSubstringPattern(char *s) {
int n = strlen(s), sub_len;
bool ans;
if (n == 1)
return false;
for (sub_len = 1; sub_len <= n / 2; sub_len++) {
if (n % sub_len) {
ans = false;
continue;
}
ans = true;
for (int i = 0; i < n; i += sub_len)
if (strncmp(s + i, s, sub_len)) {
ans = false;
break;
}
if (ans)
return true;
}
return ans;
}
int main() {
char s1[] = {"abab"}, s2[] = {"aba"}, s3[] = {"abcabcabcabc"};
printf("%d\n", repeatedSubstringPattern(s1)); // expect: 1
printf("%d\n", repeatedSubstringPattern(s2)); // expect: 0
printf("%d\n", repeatedSubstringPattern(s3)); // expect: 1
}
|