Skip to content

Instantly share code, notes, and snippets.

@Bekt
Created April 10, 2013 17:08
Show Gist options
  • Save Bekt/5356508 to your computer and use it in GitHub Desktop.
Save Bekt/5356508 to your computer and use it in GitHub Desktop.
This problem is a simpler one, so you can give it a shot right now. Write a function which, given a sentence like this: Coding for Interviews contains too many gifs. Returns the sentence with the order of the words reversed, like so: gifs. many too contains Interviews for Coding The catch is: your function should use O(1) space. What is your alg…
//NOTE: did not test AT ALL
//Time: O(N*k), k = length of the longest word in the sentence
//Space: O(1)
public class Reversed {
public static void main(String[] args) {
String sent = "Coding for Interviews contains too many gifs.";
reverse(sent);
}
static void reverse(String sent) {
for(int i=sent.length()-1; i>=0; i--) {
if(sent.charAt(i) == ' ') {
printWord(sent, i);
}
}
}
static printWord(String sent, int start) {
char curr;
while(start < sent.length() && (curr = sent.charAt(start++)) != ' ') {
System.out.print(curr);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment