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

add solution and test case for 151#148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fishercoder1534 merged 1 commit intofishercoder1534:masterfromashmichheda:151
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletionssrc/main/java/com/fishercoder/solutions/_151.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,4 +27,38 @@ public String reverseWords(String s) {
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
}
}
public static class Solution2 {
public String reverseWords(String s) {
int len = s.length();
int i = 0;
int j = 0;
String result = "";
while (i < len) {

// index i keeps track of the spaces and ignores them if found
while (i < len && s.charAt(i) == ' ') {
i++;
}
if (i == len) {
break;
}
j = i + 1;

// index j keeps track of non-space characters and gives index of the first occurrence of space after a non-space character
while (j < len && s.charAt(j) != ' ') {
j++;
}
// word found
String word = s.substring(i, j);
if(result.length() == 0) {
result = word;
}
else {
result = word + " "+ result;
}
i = j + 1;
}
return result;
}
}
}
11 changes: 10 additions & 1 deletionsrc/test/java/com/fishercoder/_151Test.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,11 +8,14 @@

public class _151Test {
private static _151.Solution1 solution1;
private static _151.Solution2 solution2;
private static String s;

@BeforeClass
public static void setup() {
public static void setup()
{
solution1 = new _151.Solution1();
solution2 = new _151.Solution2();
}

@Test
Expand All@@ -38,4 +41,10 @@ public void test4() {
s = "a b c";
assertEquals("c b a", solution1.reverseWords(s));
}

@Test
public void test5() {
s = " hello world ";
assertEquals("world hello", solution2.reverseWords(s));
}
}

[8]ページ先頭

©2009-2025 Movatter.jp