Repeated Substring Pattern
💻 coding

Repeated Substring Pattern

1 min read 264 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves checking if a string can be formed by repeating a substring multiple times.
  • 2Examples include 'abab' which returns true and 'aba' which returns false.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves checking if a string can be formed by repeating a substring multiple times."

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

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class RepeatedSubstringPatternSoln
 {
 public bool RepeatedSubstringPattern(string s)
 {
 var len = s.Length;
 for(int i = 1; i <= len / 2; i++)
 {
 if(len % i == 0)
 {
 int mul = len / i;
 var str = new StringBuilder();
 while (mul != 0)
 {
 str.Append(s.Substring(0, i));
 mul--;
 }

 if (str.ToString() == s)
 return true;
 }
 }

 return false;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Unit Tests:

using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
 [TestClass]
 public class RepeatedSubstringPatternSolnTests
 {
 [TestMethod]
 public void RepeatedSubstringPatternSoln_First()
 {
 var a = "abab";
 var output = true;
 var res = new RepeatedSubstringPatternSoln().RepeatedSubstringPattern(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void RepeatedSubstringPatternSoln_Second()
 {
 var a = "aba";
 var output = false;
 var res = new RepeatedSubstringPatternSoln().RepeatedSubstringPattern(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void RepeatedSubstringPatternSoln_Third()
 {
 var a = "abcabcabcabc";
 var output = true;
 var res = new RepeatedSubstringPatternSoln().RepeatedSubstringPattern(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void RepeatedSubstringPatternSoln_Fourth()
 {
 var a = "ababcababc";
 var output = true;
 var res = new RepeatedSubstringPatternSoln().RepeatedSubstringPattern(a);

 Assert.AreEqual(res, output);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 May 2020 · 1 min read · 264 words

Part of AskGif Blog · coding

You might also like