Created
January 24, 2017 03:31
-
-
Save primaryobjects/cc08c34967793aa9c11fe03709f80b8a to your computer and use it in GitHub Desktop.
Repeated Substring Pattern, searching for a repeatable substring within a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} str | |
* @return {boolean} | |
*/ | |
var repeatedSubstringPattern = function(str) { | |
var result = false; | |
var sameCount = 1; | |
for (var i=1; i<str.length; i++) { | |
if (str[i] === str[0]) { | |
sameCount++; | |
} | |
else { | |
break; | |
} | |
} | |
if (sameCount > 1 && sameCount === str.length) { | |
result = true; | |
} | |
else { | |
// Start the search at the 3rd letter (since we already covered cases for 1 and 2 characters above). | |
for (var i=2; i<=str.length / 2; i++) { | |
// The substring must be a divsor of the string length. This dramatically speeds up the search! | |
if (str.length % i === 0) { | |
// Get the substring. | |
var sub = str.substring(0, i); | |
skip = false; | |
// Check if the substring is found at each nth index in the string (divisor of the length). | |
for (var j=sub.length; j<=str.length - sub.length; j+=sub.length) { | |
if (str.indexOf(sub, j) !== j) { | |
// Found the substring, but not at the next divsior index. | |
result = false; | |
skip = true; | |
break; | |
} | |
} | |
// If we got this far, and j reached the end of the string evenly, we have a match! | |
if (!skip && j === str.length) { | |
result = true; | |
break; | |
} | |
} | |
} | |
} | |
return result; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a very efficient algorithm for this.
var isStringRepeating = s => (s + s).indexOf(s,1) !== s.length;