Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite01aced

Browse files
authored
added solution and test case for 151 (fishercoder1534#148)
1 parent12961cd commite01aced

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

‎src/main/java/com/fishercoder/solutions/_151.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,38 @@ public String reverseWords(String s) {
2727
returnstringBuilder.substring(0,stringBuilder.length() -1).toString();
2828
}
2929
}
30+
publicstaticclassSolution2 {
31+
publicStringreverseWords(Strings) {
32+
intlen =s.length();
33+
inti =0;
34+
intj =0;
35+
Stringresult ="";
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+
Stringword =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+
returnresult;
62+
}
63+
}
3064
}

‎src/test/java/com/fishercoder/_151Test.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,14 @@
88

99
publicclass_151Test {
1010
privatestatic_151.Solution1solution1;
11+
privatestatic_151.Solution2solution2;
1112
privatestaticStrings;
1213

1314
@BeforeClass
14-
publicstaticvoidsetup() {
15+
publicstaticvoidsetup()
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+
publicvoidtest5() {
47+
s =" hello world ";
48+
assertEquals("world hello",solution2.reverseWords(s));
49+
}
4150
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp