-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsInString.java
More file actions
51 lines (45 loc) · 1.18 KB
/
ReverseWordsInString.java
File metadata and controls
51 lines (45 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package codingInterview;
public class ReverseWordsInString {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "the sky is so blue";
String reverseStr = reverseWords(str);
System.out.println(reverseStr);
}
private static String reverseWords(String str) {
// TODO Auto-generated method stub
if (str == null || str.length() == 0) {
return null;
}
String[] splitArray = str.split(" ");
int length = splitArray.length;
int left = 0;
int right = length - 1;
// there is no need to reverse the array
// while (left < right) {
// String tmp = splitArray[left];
// splitArray[left] = splitArray[right];
// splitArray[right] = tmp;
//
// left++;
// right--;
// }
StringBuilder builder = new StringBuilder();
// for (int i = 0; i < length; i++) {
// if (i != length - 1) {
// builder.append(splitArray[i] + " ");
// } else {
// builder.append(splitArray[i]);
// }
// }
// append the array string from right to left
for (int i = length - 1; i >= 0; i--) {
if (i != 0) {
builder.append(splitArray[i] + " ");
} else {
builder.append(splitArray[i]);
}
}
return builder.toString();
}
}