Repeated Substring Pattern

This commit is contained in:
Sainnhe Park 2022-12-01 21:03:25 +08:00
parent 9ce930f11f
commit 8485bba8c0
5 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0459_REPEATED_SUBSTRING_PATTERN_HPP
#define S0459_REPEATED_SUBSTRING_PATTERN_HPP
#include <string>
using namespace std;
class S0459 {
public:
bool repeatedSubstringPattern(string s);
void getNext(string &s, int *next);
};
#endif

View File

@ -12,6 +12,7 @@
- [翻转字符串里的单词](./reverse_words_in_a_string.md)
- [左旋转字符串](./reverse_left_words.md)
- [KMP](./kmp.md)
- [重复的子字符串](./repeated_substring_pattern.md)
# 经典代码

View File

@ -0,0 +1,23 @@
# 重复的子字符串
[459. Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/)
给定一个非空的字符串判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母并且长度不超过10000。
示例:
输入: "abab"
输出: True
解释: 可由子字符串 "ab" 重复两次构成。
## 方法一
将两个 s 拼接在一起,如果里面还出现一个 s 的话,就认为是由重复字符串构成的。
## 方法二
假设 s 是由 n 个 x 构成的,那么它的最长公共前后缀的长度是 `(n - 1) * len(x)`
也就是说 `len(s) % (len(s) - (n - 1) * len(x)) == 0`

View File

@ -0,0 +1,32 @@
#include "s0459_repeated_substring_pattern.hpp"
void S0459::getNext(string &s, int *next) {
int j{0};
int len = s.size();
next[0] = 0;
for (int i{1}; i < len; ++i) {
while (j > 0 && s[i] != s[j]) {
j = next[j - 1];
}
if (s[i] == s[j]) {
++j;
}
next[i] = j;
}
}
bool S0459::repeatedSubstringPattern(string s) {
int len = s.size();
if (len <= 1) {
return false;
}
int next[len];
getNext(s, next);
if (next[len - 1] == 0) {
return false;
} else if (len % (len - next[len - 1]) == 0) {
return true;
} else {
return false;
}
}

View File

@ -0,0 +1,31 @@
#include "s0459_repeated_substring_pattern.hpp"
#include <gtest/gtest.h>
TEST(Problem459, Case1) {
string s{"abab"};
bool expected{true};
S0459 solution;
EXPECT_EQ(solution.repeatedSubstringPattern(s), expected);
}
TEST(Problem459, Case2) {
string s{"aba"};
bool expected{false};
S0459 solution;
EXPECT_EQ(solution.repeatedSubstringPattern(s), expected);
}
TEST(Problem459, Case3) {
string s{"abcabcabcabc"};
bool expected{true};
S0459 solution;
EXPECT_EQ(solution.repeatedSubstringPattern(s), expected);
}
TEST(Problem459, Case4) {
string s{"abac"};
bool expected{false};
S0459 solution;
EXPECT_EQ(solution.repeatedSubstringPattern(s), expected);
}