avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-459-Repeated Substring Pattern
文章

Leetcode-459-Repeated Substring Pattern

Posted 2022-07-11
3~4 min read

Repeated Substring Pattern

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

Description:

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

Idea:

Step1: us KMP to get the prefix table of the string.

Step2: The length of the string - the longest length(suffix == prefix) of the string = the repeated substring’s length

Step3: If the length of string % the repeated substring’s length =0, it menas the original strings consists of the substring.

Code:

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        if (s.length()==0){
            return false;
        }
        char[] sc = s.toCharArray();
        int j = 0;
        int length = s.length();
        int[] result = new int[s.length()+1];
        for(int i =1; i<sc.length; i++){
            while(j>0 && sc[i] != sc[j]){
                j = result[j-1];
            }
            if(sc[i] == sc[j]){
                j++;
            }
        result[i] = j;
        }
        
        if(result[length-1] > 0 && length%(length-result[length-1]) == 0){
            return true;
        }
        return false;

    }
}
Leetcode
Leetcode String
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] 🔗 LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] 🔗 LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] 🔗 LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Leetcode-28-Implement strStr()-KMP

NEWER

DSA-Learning-https://programmercarl.com/

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents