Last active
June 2, 2020 00:12
-
-
Save SanthoshBabuMR/8b251d8202bcecd43ec58c9df330b127 to your computer and use it in GitHub Desktop.
Find 'aeiou' in sentence
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
function smallestSubStr(sentence, str) { | |
if(!sentence || !str) { return null; } | |
let beginCharacter = str[0].toLowerCase(); | |
let probableMatches = []; | |
let smallestSubStrMap = { | |
len: Number.MAX_SAFE_INTEGER, | |
text: null | |
}; | |
for(let index = 0; index < sentence.length; index++ ) { | |
let character = sentence[index].toLowerCase(); | |
let isBeginCharacter = character === beginCharacter; | |
if (isBeginCharacter) { | |
let nextLookUpIndex = 1; | |
let probableMatch = { | |
startsAtIndex: index, | |
nextLookUpIndex: nextLookUpIndex | |
} | |
probableMatches.push(probableMatch); | |
} else { | |
probableMatches = probableMatches.filter(probableMatch => { | |
let lookUpIndex = probableMatch.nextLookUpIndex; | |
let isCharacterMatching = character === str[lookUpIndex].toLowerCase(); | |
let isEndCharacter = isCharacterMatching && lookUpIndex === str.length-1; | |
if (isEndCharacter) { | |
let lengthOfSubStrFound = (index + 1) - probableMatch.startsAtIndex; | |
let isSmallerLengthSubStr = smallestSubStrMap.len >= lengthOfSubStrFound; | |
if (isSmallerLengthSubStr) { | |
let endIndex = index + 1; | |
smallestSubStrMap.len = lengthOfSubStrFound; | |
smallestSubStrMap.text = sentence.substring(probableMatch.startsAtIndex, endIndex) | |
} | |
return false; | |
} | |
if (isCharacterMatching) { | |
probableMatch.nextLookUpIndex = probableMatch.nextLookUpIndex + 1; | |
} | |
return true; | |
}); | |
} | |
}; | |
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