Skip to content

Instantly share code, notes, and snippets.

@tiggreen
Created January 24, 2016 15:44
Show Gist options
  • Save tiggreen/abecbe3e9aff40f57148 to your computer and use it in GitHub Desktop.
Save tiggreen/abecbe3e9aff40f57148 to your computer and use it in GitHub Desktop.
Misht Community #1
import static org.junit.Assert.assertEquals;
import java.util.*;
import java.lang.*;
import java.io.*;
/*
"Given an input string s, reverse words in a string."
Do this in-place without allocating an extra space.
The input string doesn't contain any leading or trailing
spaces and all words are separated by a single space.
For example, given string "the weather is cold today",
return "today cold is weather the".
O(n) cpu, O(n) space - reverse the entire string first,
then reverse each word
@author rcmccartney
*/
class Ideone {
public static String doIt(String toReverse) {
StringBuilder stb = new StringBuilder(toReverse);
// could just use stringbuilder reverse, but for completeness..
reverseStr(stb, 0, stb.length()-1);
int start = 0, end = 0;
while (start < stb.length()) {
while (end < stb.length() && stb.charAt(end) != ' ') {
end++;
}
reverseStr(stb, start, end-1);
start = ++end; // skip whitespace and start next word
}
return stb.toString();
}
public static void reverseStr(StringBuilder stb, int start, int end) {
char temp;
while (start < end) {
temp = stb.charAt(end);
stb.setCharAt(end--, stb.charAt(start));
stb.setCharAt(start++, temp);
}
}
public static void main (String[] args) throws java.lang.Exception {
// assertEquals seems broken on ideone.com, will just print them
System.out.println("1. " + doIt("the weather is cold today"));
System.out.println("2. " + doIt("oneword"));
System.out.println("3. " + doIt("A longer string periods may mess it up."));
System.out.println("4. " + doIt(""));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment