Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Update (2015-02-12):
For C programmers:try to solve it in-place in O(1) space.
Click to show Clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.
- Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
- How about multiple spaces between and words?
Reduce them to a single space in the reversed string.
Problem Analysis: 1, the generated word inside no space!
2. Input string, including header or trailing space? Yes, you can't include these spaces when reversing.
3, two words between a number of spaces? Leave only one space analysis: two methods:
Code Listing 1:
String[] parts = s.trim().split("\\s+");//去除前后的空格+去除里面的空格,得到一个没有空格的字符串
String out = "";
if (parts.length > 0) { //从后往前输出,加入字符串
for (int i = parts.length - 1; i > 0; i--)
{ out += parts[i] + " "; }
out += parts[0]; }
return out;
Code Listing 2: By reversing the entire string, to remove the space that does not match the topic;
and invert every word;
Package Leetcode;
public class Reversewordsinastring {
Reverses the "an" array and returns the input array for convenience
public static char[] Reverse (char[] arr, int i, int j) {
while (I < j) {
char tmp = arr[i];
arr[i++] = Arr[j];
arr[j--] = tmp;
}
return arr;
}
public static string Reversewords (string s) {
Reverse the whole string and convert to char array
char[] str = reverse (S.tochararray (), 0, S.length ()-1);
System.out.println (Str.tostring ());
int start = 0, end = 0; Start and end positions of a current word
for (int i = 0; i < str.length; i++) {
if (str[i]! = ") {//If the current char are letter
str[end++] = Str[i]; Just move this letter to the next free POS
} else if (i > 0 && str[i-1]! = ") {//If the first space after word
Reverse (str, start, end-1); Reverse the word
str[end++] = "; And put the space after it
start = end; Move start position further for the next word
}
}
System.out.println (s);
System.out.println (S.length ());
Reverse (str, start, end-1);
Why do you want to add the above step??? Looks like there's no difference
Reverse the tail word if it ' s there
Here's a ugly return just because we need to return Java ' s String
Also as there could is spaces at the end of original string
We need to consider redundant space we have put there before
System.out.println (s);
System.out.println (S.length ());
return new String (str, 0, end > 0 && str[end-1] = = '? End-1: End);
}
public static void Main (string[] args) {
System.out.println (Reversewords ("he ll o world!!"));
System.out.println (Reversewords ("he ll o world!!"). Length ());
}
}
Leetcode-reverse Words in a String