Created
November 11, 2018 17:58
-
-
Save AlexeiDarmin/677a47a9179cee0f46a8e38184f3a551 to your computer and use it in GitHub Desktop.
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring().
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
/* | |
Assume you have a method called isSubstring() which checks if one word is a subtring of another. | |
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to | |
isSubstring(). Eg "waterbottle is a rotation of erbottlewat" | |
*/ | |
function checkSubstr(s1: string, s2: string): boolean { | |
if (s1.length !== s2.length) { | |
return false | |
} | |
const rotationByIndex = new Map() | |
for (let i = 0; i < s2.length; ++i) { | |
const char = s2[i] | |
for (let rIndex = 0; rIndex <= i; ++rIndex) { | |
if (rIndex === 0 && !rotationByIndex.get(i)) { | |
rotationByIndex.set(i, []) | |
} | |
const rotation = rotationByIndex.get(rIndex) | |
if (!rotation) { | |
continue | |
} | |
if (char === 'a' && rIndex === 1) debugger | |
if (char === s1[rotation.length]) { | |
rotation.push(char) | |
} else { | |
rotationByIndex.delete(rIndex) | |
} | |
} | |
} | |
const keys = Array.from(rotationByIndex.keys()) | |
if (keys.length > 1) throw 'should never happen' | |
if (keys.length === 0) return false | |
const key = parseInt(keys[0]) | |
const firstSlice = s2.slice(0, key) | |
const secondSlice = s2.slice(key, s2.length) | |
return s1.includes(secondSlice.concat(firstSlice)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment