aboutsummaryrefslogtreecommitdiff
path: root/repeated_substring_pattern.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /repeated_substring_pattern.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'repeated_substring_pattern.cpp')
-rw-r--r--repeated_substring_pattern.cpp31
1 files changed, 31 insertions, 0 deletions
diff --git a/repeated_substring_pattern.cpp b/repeated_substring_pattern.cpp
new file mode 100644
index 0000000..4e2d8d8
--- /dev/null
+++ b/repeated_substring_pattern.cpp
@@ -0,0 +1,31 @@
+// 459. Repeated Substring Pattern
+#include "leetcode.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.
+ */
+
+class Solution {
+public:
+ bool repeatedSubstringPattern(string s) {
+ int i = 1, j = 0, n = s.size();
+ vector<int> dp(n + 1, 0);
+ while (i < n) {
+ if (s[i] == s[j])
+ dp[++i] = ++j;
+ else if (!j)
+ i++;
+ else
+ j = dp[j];
+ }
+ return dp[n] && dp[n] % (n - dp[n]) == 0;
+ }
+};
+
+int main() {
+ Solution obj;
+ printf("%d\n", obj.repeatedSubstringPattern("abab")); // expect: 1
+ printf("%d\n", obj.repeatedSubstringPattern("aba")); // expect: 0
+ printf("%d\n", obj.repeatedSubstringPattern("abcabcabcabc")); // expect: 1
+}