557. Reverse Words in a String III (Easy)

https://leetcode.com/problems/reverse-words-in-a-string-iii/

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

Example 1:

```Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
```

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Solutions

``````class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");

String ans = "";
for (String str : strs) {
ans += reverseString(str.toCharArray()) + " ";
}

return ans.trim();
}

private String reverseString(char[] s) {
if (s == null || s.length <= 1) {
return String.valueOf(s);
}

int lptr = 0;
int rptr = s.length - 1;
while (lptr < rptr) {
swap(s, lptr, rptr);

lptr++;
rptr--;
}

return String.valueOf(s);
}

private void swap(char[] s, int x, int y) {
char tmp = s[x];
s[x] = s[y];
s[y] = tmp;
}
}
``````