Last active
September 23, 2021 08:53
-
-
Save hk-skit/d53ea67a1cee58474fe9d2d5abbbd56f to your computer and use it in GitHub Desktop.
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
// Given a string and a set of delimiters, reverse the words in the string while maintaining | |
// the relative order of the delimiters. For example, given "hello/world:here", return "here/world:hello". | |
// Follow-up: Does your solution work for the following cases: "hello/world:here/", "hello//world:here" | |
const reverseWords = (string, delimiters) => { | |
const aux = []; | |
let word = ''; | |
// O(n) | |
for (const str of string) { | |
if (!delimiters.has(str)) { | |
word += str; | |
continue; | |
} | |
if (word.length) { | |
aux.push(word); | |
word = ''; | |
} | |
aux.push(str); | |
} | |
if (word.length) { | |
aux.push(word); | |
} | |
let start = 0; | |
let end = aux.length - 1; | |
// O(n) | |
while (start !== end) { | |
const a = aux[start]; | |
if (delimiters.has(a)) { | |
start += 1; | |
continue; | |
} | |
const b = aux[end]; | |
if (delimiters.has(b)) { | |
end -= 1; | |
continue; | |
} | |
[aux[start], aux[end]] = [aux[end], aux[start]]; | |
start += 1; | |
end -= 1; | |
} | |
return aux.join(''); | |
}; | |
// [ 'hello', '/', 'world', ':', 'here' ] | |
// | |
[ | |
'hello/world:here', | |
'hello/world:here/', | |
'hello//world:here', | |
':hello/world:here', | |
].forEach((string) => | |
console.log(string, reverseWords(string, new Set(['/', ':']))) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment