Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package g0501_0600.s0557_reverse_words_in_a_string_iii;

// #Easy #String #Two_Pointers

public class Solution {
public String reverseWords(String s) {
int l = 0;
int r = 0;
int len = s.length();
char[] ch = s.toCharArray();
for (int i = 0; i <= len; i++) {
if (i == len || ch[i] == ' ') {
l = r;
r = i;
reverse(ch, l, r - 1);
r++;
}
}
return new String(ch);
}

private void reverse(char[] s, int l, int r) {
char c;
while (r > l) {
c = s[l];
s[l++] = s[r];
s[r--] = c;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
557\. Reverse Words in a String III

Easy

Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

**Example 1:**

**Input:** s = "Let's take LeetCode contest"

**Output:** "s'teL ekat edoCteeL tsetnoc"

**Example 2:**

**Input:** s = "God Ding"

**Output:** "doG gniD"

**Constraints:**

* <code>1 <= s.length <= 5 * 10<sup>4</sup></code>
* `s` contains printable **ASCII** characters.
* `s` does not contain any leading or trailing spaces.
* There is **at least one** word in `s`.
* All the words in `s` are separated by a single space.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package g0501_0600.s0557_reverse_words_in_a_string_iii;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void reverseWords() {
assertThat(
new Solution().reverseWords("Let's take LeetCode contest"),
equalTo("s'teL ekat edoCteeL tsetnoc"));
}

@Test
void reverseWords2() {
assertThat(new Solution().reverseWords("God Ding"), equalTo("doG gniD"));
}
}