File tree Expand file tree Collapse file tree 2 files changed +51
-1
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -24,7 +24,7 @@ public String reverseWords(String s) {
24
24
while (!stack .isEmpty ()) {
25
25
stringBuilder .append (stack .pollLast ()).append (" " );
26
26
}
27
- return stringBuilder .substring (0 , stringBuilder .length () - 1 ). toString () ;
27
+ return stringBuilder .substring (0 , stringBuilder .length () - 1 );
28
28
}
29
29
}
30
30
@@ -61,4 +61,44 @@ public String reverseWords(String s) {
61
61
return result ;
62
62
}
63
63
}
64
+
65
+ public static class Solution3 {
66
+ public String reverseWords (String s ) {
67
+ s = s .trim ();
68
+ StringBuilder sb = new StringBuilder ();
69
+ for (int i = 0 ; i < s .length (); i ++) {
70
+ if (s .charAt (i ) == ' ' && sb .length () > 0 && sb .charAt (sb .length () - 1 ) == ' ' ) {
71
+ continue ;
72
+ } else {
73
+ sb .append (s .charAt (i ));
74
+ }
75
+ }
76
+ int left = 0 ;
77
+ int right = sb .length () - 1 ;
78
+ while (left < right ) {
79
+ char tmp = sb .charAt (left );
80
+ sb .setCharAt (left , sb .charAt (right ));
81
+ sb .setCharAt (right , tmp );
82
+ left ++;
83
+ right --;
84
+ }
85
+ int boundary = 0 ;
86
+ while (boundary < sb .length ()) {
87
+ left = boundary ;
88
+ while (boundary < sb .length () && sb .charAt (boundary ) != ' ' ) {
89
+ boundary ++;
90
+ }
91
+ right = boundary - 1 ;
92
+ while (left < right ) {
93
+ char tmp = sb .charAt (left );
94
+ sb .setCharAt (left , sb .charAt (right ));
95
+ sb .setCharAt (right , tmp );
96
+ left ++;
97
+ right --;
98
+ }
99
+ boundary ++;
100
+ }
101
+ return sb .toString ();
102
+ }
103
+ }
64
104
}
Original file line number Diff line number Diff line change 9
9
public class _151Test {
10
10
private static _151 .Solution1 solution1 ;
11
11
private static _151 .Solution2 solution2 ;
12
+ private static _151 .Solution3 solution3 ;
12
13
private static String s ;
13
14
14
15
@ BeforeClass
15
16
public static void setup () {
16
17
solution1 = new _151 .Solution1 ();
17
18
solution2 = new _151 .Solution2 ();
19
+ solution3 = new _151 .Solution3 ();
18
20
}
19
21
20
22
@ Test
@@ -45,5 +47,13 @@ public void test4() {
45
47
public void test5 () {
46
48
s = " hello world " ;
47
49
assertEquals ("world hello" , solution2 .reverseWords (s ));
50
+ assertEquals ("world hello" , solution3 .reverseWords (s ));
51
+ }
52
+
53
+ @ Test
54
+ public void test6 () {
55
+ s = "Bob Loves Alice " ;
56
+ assertEquals ("Alice Loves Bob" , solution2 .reverseWords (s ));
57
+ assertEquals ("Alice Loves Bob" , solution3 .reverseWords (s ));
48
58
}
49
59
}
You can’t perform that action at this time.
0 commit comments