Skip to content

Commit 22c8dd1

Browse files
add a solution for 151
1 parent 0b55353 commit 22c8dd1

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

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

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public String reverseWords(String s) {
2424
while (!stack.isEmpty()) {
2525
stringBuilder.append(stack.pollLast()).append(" ");
2626
}
27-
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
27+
return stringBuilder.substring(0, stringBuilder.length() - 1);
2828
}
2929
}
3030

@@ -61,4 +61,44 @@ public String reverseWords(String s) {
6161
return result;
6262
}
6363
}
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+
}
64104
}

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@
99
public class _151Test {
1010
private static _151.Solution1 solution1;
1111
private static _151.Solution2 solution2;
12+
private static _151.Solution3 solution3;
1213
private static String s;
1314

1415
@BeforeClass
1516
public static void setup() {
1617
solution1 = new _151.Solution1();
1718
solution2 = new _151.Solution2();
19+
solution3 = new _151.Solution3();
1820
}
1921

2022
@Test
@@ -45,5 +47,13 @@ public void test4() {
4547
public void test5() {
4648
s = " hello world ";
4749
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));
4858
}
4959
}

0 commit comments

Comments
 (0)