首页 技术 正文
技术 2022年11月8日
0 收藏 827 点赞 1,410 浏览 1868 个字

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"Output: TrueExplanation: It's the substring "ab" twice.

Example 2:

Input: "aba"Output: False

Example 3:

Input: "abcabcabcabc"Output: TrueExplanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

这道题给了我们一个字符串,问其是否能拆成n个重复的子串。那么既然能拆分成多个子串,那么每个子串的长度肯定不能大于原字符串长度的一半,那么我们可以从原字符串长度的一半遍历到1,如果当前长度能被总长度整除,说明可以分成若干个子字符串,我们将这些子字符串拼接起来看跟原字符串是否相等。 如果拆完了都不相等,返回false。

解法一:

class Solution {
public:
bool repeatedSubstringPattern(string str) {
int n = str.size();
for (int i = n / ; i >= ; --i) {
if (n % i == ) {
int c = n / i;
string t = "";
for (int j = ; j < c; ++j) {
t += str.substr(, i);
}
if (t == str) return true;
}
}
return false;
}
};

下面这种方法是参考的网上的这个帖子,原作者说是用的KMP算法,LeetCode之前也有一道应用KMP算法来解的题Shortest Palindrome,但是感觉那道题才是KMP算法。这道题也称为KMP算法感觉怪怪的(关于KMP的详细介绍请参见从头到尾彻底理解KMP,也可以看博主自己写的一篇KMP Algorithm 字符串匹配算法KMP小结),KMP算法中的next数组是找当前位置的最大相同前缀后缀的个数,而这道题维护的一位数组dp[i]表示,到位置i-1为止的重复字符串的字符个数,不包括被重复的那个字符串,什么意思呢,我们举个例子,比如”abcabc”的dp数组为[0 0 0 0 1 2 3],dp数组长度要比原字符串长度多一个。那么我们看最后一个位置数字为3,就表示重复的字符串的字符数有3个。如果是”abcabcabc”,那么dp数组为[0 0 0 0 1 2 3 4 5 6],我们发现最后一个数字为6,那么表示重复的字符串为“abcabc”,有6个字符。那么怎么通过最后一个数字来知道原字符串是否由重复的子字符串组成的呢,首先当然是最后一个数字不能为0,而且还要满足dp[n] % (n – dp[n]) == 0才行,因为n – dp[n]是一个子字符串的长度,那么重复字符串的长度和肯定是一个子字符串的整数倍,参见代码如下:

解法二:

class Solution {
public:
bool repeatedSubstringPattern(string str) {
int i = , j = , n = str.size();
vector<int> dp(n + , );
while (i < n) {
if (str[i] == str[j]) dp[++i] = ++j;
else if (j == ) ++i;
else j = dp[j];
}
return dp[n] && (dp[n] % (n - dp[n]) == );
}
};

类似题目:

Implement strStr()

Repeated String Match

参考资料:

https://discuss.leetcode.com/topic/68498/one-line-with-regex/2

https://discuss.leetcode.com/topic/67992/java-simple-solution-with-explanation

https://discuss.leetcode.com/topic/67652/c-o-n-using-kmp-32ms-8-lines-of-code-with-brief-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295