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”
classSolution {
public String reverseWords(String s) {
Stack<String> stack =new Stack<>();
Queue<String> queue =new LinkedList<>();
StringBuilder word =new StringBuilder();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isLetterOrDigit(c)) {
word.append(c);
i++;
} else {
if (word.length() > 0) {
stack.push(word.toString());
}
word =new StringBuilder(); // clear word for next word StringBuilder delim =new StringBuilder();
delim.append(c);
i++;
// tracking continuous delimiter to add to queuewhile (i < s.length() &&!Character.isLetterOrDigit(s.charAt(i))) {
delim.append(c);
i++;
}
queue.add(delim.toString());
}
}
// if string ends with wordsif (word.length() != 0) {
stack.push(word.toString());
}
boolean isWordFirst = Character.isLetterOrDigit(s.charAt(0));
StringBuilder sb =new StringBuilder();
// if word is not first, add 1 entry from queueif (!isWordFirst) {
if (!queue.isEmpty()) {
sb.append(queue.remove());
}
}
// now put 1 element from either till not emptywhile (!stack.isEmpty() ||!queue.isEmpty()) {
if (!stack.isEmpty()) {
sb.append(stack.pop());
}
if (!queue.isEmpty()) {
sb.append(queue.remove());
}
}
return sb.toString();
}
}