Last active
August 29, 2015 14:15
-
-
Save dmnugent80/d2b898d0a1890658fad6 to your computer and use it in GitHub Desktop.
Reverse Sentence Simple
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
//In-Place | |
public class ReverseSentenceInPlace | |
{ | |
public static void main(String[] args) | |
{ | |
String str = "Hello, I would, like, to.....,... reverse! This, sentence.,,"; | |
String reversed = reverseSentence(str); | |
System.out.print(reversed); | |
} | |
public static String reverseSentence(String str){ | |
char[] arr = str.toCharArray(); | |
reverse(arr, 0, arr.length-1); | |
for (int i = 0; i < arr.length; i++){ | |
int j = i; | |
while (j < arr.length && arr[j] != ' '){ | |
j++; | |
} | |
reverse(arr, i, j-1); | |
i = j; | |
} | |
return new String(arr); | |
} | |
public static void reverse(char[] arr, int start, int end){ | |
while (start < end){ | |
char temp = arr[start]; | |
arr[start] = arr[end]; | |
arr[end] = temp; | |
start++; | |
end--; | |
} | |
} | |
} | |
/*output: | |
sentence.,, This, reverse! to.....,... like, would, I Hello, | |
*/ | |
//using split method | |
public class Solution { | |
public String reverseWords(String s) { | |
s = s.trim(); | |
String[] words = s.split(" +"); | |
StringBuffer strBuff = new StringBuffer(); | |
if (words.length != 0) { | |
for (int i = words.length - 1; i > 0; i--) { | |
strBuff.append(words[i] + " "); | |
} | |
strBuff.append(words[0]); | |
} | |
return strBuff.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment