Created
April 10, 2013 17:08
-
-
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…
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
| //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