459.Repeated-Substring-Pattern

459. Repeated Substring Pattern

题目地址

https://leetcode.com/problems/repeated-substring-pattern/

题目描述

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.)

代码

Approach #1 Regex

Time: O(N^2) && Space: O(1)

because we use greedy regex pattern. Once we have a +, the pattern is greedy.

The difference between the greedy and the non-greedy match is the following:

  • the non-greedy match will try to match as few repetitions of the quantified pattern as possible.

  • the greedy match will try to match as many repetitions as possible.

The worst-case situation here is to check all possible pattern lengths from N to 1 that would result in O(N^2) time complexity.

import java.util.regex.Pattern;
class Solution {
  public boolean repeatedSubstringPattern(String s) {
        Pattern pat = Pattern.compile("^(.+)\\1+$")
  }
}

Approach #2 Concatenation

Repeated pattern string looks like PatternPattern, and the others like Pattern1Pattern2.

Let's double the input string:

PatternPattern` --> `PatternPatternPatternPattern
Pattern1Pattern2` --> `Pattern1Pattern2Pattern1Pattern2

Now let's cut the first and the last characters in the doubled string:

PatternPattern` --> `*atternPatternPatternPatter*
Pattern1Pattern2` --> `*attern1Pattern2Pattern1Pattern*

It's quite evident that if the new string contains the input string, the input string is a repeated pattern string.

class Solution {
  public boolean repeatedSubstringPattern(String s) {
    return (s + s).substring(1, 2 * s.length() - 1).contains(s);
  }
}

Last updated