diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /repeated_substring_pattern.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'repeated_substring_pattern.c')
-rw-r--r-- | repeated_substring_pattern.c | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/repeated_substring_pattern.c b/repeated_substring_pattern.c new file mode 100644 index 0000000..a5d2d52 --- /dev/null +++ b/repeated_substring_pattern.c @@ -0,0 +1,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 +} |