File tree 2 files changed +44
-1
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +44
-1
lines changed Original file line number Diff line number Diff line change @@ -27,4 +27,38 @@ public String reverseWords(String s) {
27
27
return stringBuilder .substring (0 , stringBuilder .length () - 1 ).toString ();
28
28
}
29
29
}
30
+ public static class Solution2 {
31
+ public String reverseWords (String s ) {
32
+ int len = s .length ();
33
+ int i = 0 ;
34
+ int j = 0 ;
35
+ String result = "" ;
36
+ while (i < len ) {
37
+
38
+ // index i keeps track of the spaces and ignores them if found
39
+ while (i < len && s .charAt (i ) == ' ' ) {
40
+ i ++;
41
+ }
42
+ if (i == len ) {
43
+ break ;
44
+ }
45
+ j = i + 1 ;
46
+
47
+ // index j keeps track of non-space characters and gives index of the first occurrence of space after a non-space character
48
+ while (j < len && s .charAt (j ) != ' ' ) {
49
+ j ++;
50
+ }
51
+ // word found
52
+ String word = s .substring (i , j );
53
+ if (result .length () == 0 ) {
54
+ result = word ;
55
+ }
56
+ else {
57
+ result = word + " " + result ;
58
+ }
59
+ i = j + 1 ;
60
+ }
61
+ return result ;
62
+ }
63
+ }
30
64
}
Original file line number Diff line number Diff line change 8
8
9
9
public class _151Test {
10
10
private static _151 .Solution1 solution1 ;
11
+ private static _151 .Solution2 solution2 ;
11
12
private static String s ;
12
13
13
14
@ BeforeClass
14
- public static void setup () {
15
+ public static void setup ()
16
+ {
15
17
solution1 = new _151 .Solution1 ();
18
+ solution2 = new _151 .Solution2 ();
16
19
}
17
20
18
21
@ Test
@@ -38,4 +41,10 @@ public void test4() {
38
41
s = "a b c" ;
39
42
assertEquals ("c b a" , solution1 .reverseWords (s ));
40
43
}
44
+
45
+ @ Test
46
+ public void test5 () {
47
+ s = " hello world " ;
48
+ assertEquals ("world hello" , solution2 .reverseWords (s ));
49
+ }
41
50
}
You can’t perform that action at this time.
0 commit comments