Last active
June 2, 2020 00:12
-
-
Save SanthoshBabuMR/3c8bc60ab490c26fbc3ac345f8de9427 to your computer and use it in GitHub Desktop.
Find 'aeiou' in sentence
This file contains hidden or 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
function smallestSubStr(sentence, str) { | |
if(!sentence || !str) { return null; } | |
let searchStrIndex = 0; | |
let startsAtIndex; | |
let smallestSubStrMap = { | |
len: Number.MAX_SAFE_INTEGER, | |
text: null | |
}; | |
for(let index = 0; index < sentence.length; index++ ) { | |
let isCharacterMatching = sentence[index].toLowerCase() === str[searchStrIndex].toLowerCase(); | |
let isStartCharacter = isCharacterMatching && startsAtIndex == undefined; | |
let isEndCharacter = isCharacterMatching && searchStrIndex == str.length -1; | |
if (isStartCharacter) { | |
startsAtIndex = index; | |
} | |
if (isCharacterMatching) { | |
searchStrIndex = searchStrIndex + 1; | |
} | |
if (isEndCharacter) { | |
let strWidth = index - startsAtIndex; | |
let isSmallestLengthSubStr = smallestSubStrMap.len > strWidth; | |
if (isSmallestLengthSubStr) { | |
let endIndex = index + 1; | |
smallestSubStrMap.len = strWidth; | |
smallestSubStrMap.text = sentence.substring(startsAtIndex, endIndex); | |
startsAtIndex = undefined; | |
} | |
searchStrIndex = 0; | |
} | |
} | |
if (smallestSubStrMap.len === Number.MAX_SAFE_INTEGER) { | |
return null; | |
} | |
return smallestSubStrMap.text; | |
} | |
let sentences = [ '', 'au', 'aeiou', 'Hello Aeio and U', | |
'My name is santhosh and you are?', 'My name is santhosh and you are?! aeiou']; | |
let str = 'aeiou'; | |
sentences.forEach(sentence => console.log(`\nsmallestSubStr('${sentence}', '${str}')`, '->', smallestSubStr(sentence, str))); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment