Reverse Words
Write a function that reverses the order of the words in a string. For example, your function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”. Assume that all words are space delimited and treat punctuation the same as letters.
class Solution {
public static String reverseWords(char[] str) {
if (str == null || str.length == 0)
return null;
reverseStr(str, 0, str.length - 1);
int start = 0;
int end = 0;
while (end < str.length) {
if (str[end] != ' ') {
start = end;
while ( end < str.length && str[end] != ' ')
end++;
end--;
reverseStr(str, start, end);
}
end++;
}
return new String(str);
}
private static void reverseStr(char[] str, int start, int end) {
while (end > start) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
end--;
start++;
}
}
public static void main(String[] args) {
String str = "Do or do not, there is no try.";
char[] ch = str.toCharArray();
System.out.print(reverseWords(ch));
}
}