Skip to content

Instantly share code, notes, and snippets.

@hk-skit
Last active September 23, 2021 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hk-skit/d53ea67a1cee58474fe9d2d5abbbd56f to your computer and use it in GitHub Desktop.
Save hk-skit/d53ea67a1cee58474fe9d2d5abbbd56f to your computer and use it in GitHub Desktop.
// 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