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);
}
}
}



