File tree Expand file tree Collapse file tree 2 files changed +44
-1
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 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) {
2727 return stringBuilder .substring (0 , stringBuilder .length () - 1 ).toString ();
2828 }
2929 }
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+ }
3064}
Original file line number Diff line number Diff line change 88
99public class _151Test {
1010 private static _151 .Solution1 solution1 ;
11+ private static _151 .Solution2 solution2 ;
1112 private static String s ;
1213
1314 @ BeforeClass
14- public static void setup () {
15+ public static void setup ()
16+ {
1517 solution1 = new _151 .Solution1 ();
18+ solution2 = new _151 .Solution2 ();
1619 }
1720
1821 @ Test
@@ -38,4 +41,10 @@ public void test4() {
3841 s = "a b c" ;
3942 assertEquals ("c b a" , solution1 .reverseWords (s ));
4043 }
44+
45+ @ Test
46+ public void test5 () {
47+ s = " hello world " ;
48+ assertEquals ("world hello" , solution2 .reverseWords (s ));
49+ }
4150}
You can’t perform that action at this time.
0 commit comments