LeetCode 459: Repeated Substring Pattern (c++)

一:题目

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: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

二:解体分析

思路一:笨方法,时间复杂度O(n2),截取前1,2,...,s.length()/2-1,长度,查看拼接后的字符串是否与源字符串相同

思路二:KMP算法,时间复杂度O(n) 详细介绍可参考博客  从头到尾彻底理解KMP

三:代码实现

方法一:

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        
        //符合条件,则子串至少要重复两次,即子串最大长度是从开始位置到字符串的中间位置
        int i=0;
        int j;
        string substring;
        string multipleString;
        
        for(i=0;i

方法二(详见博客 点击打开链接)

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
   
        //KMP算法
        int len = s.length();
        int next[len+1];
        next[0] = -1;
        int j = 0, k = -1;
        
        while( j


你可能感兴趣的:(LeetCode-Easy)