leetcode-Reverse-Words-in-a-String-III

2017-08-23
leetcode

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.

1
2
3
4
5

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {

public String reverseSingle(String c){
char[] str = c.toCharArray();
int i = 0;
char tmp;

while(i < c.length()/2){
tmp = str[i];
str[i] = str[c.length()-1-i];
str[c.length()-1-i] = tmp;
i++;
}
return new String(str);
}

public String reverseWords(String s) {

String[] m = s.split(" ");

int i;
String res = "";

for (i = 0; i < m.length; i++){

if (res.length() == 0){
res += reverseSingle(m[i]);
}else{
res = res + " " + reverseSingle(m[i]);
}
}
return res;
}
}

someone post another way using the natural StringBuilder class,
it has ‘reverse’ method,

1
2
3
4
5
6
7
8

public String reverseWords(String s) {
String[] str = s.split(" ");
for (int i = 0; i < str.length; i++) str[i] = new StringBuilder(str[i]).reverse().toString();
StringBuilder result = new StringBuilder();
for (String st : str) result.append(st + " ");
return result.toString().trim();
}