Reverse Words in a String I
Title Description
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.
Code
1 |
public class Solution { // consider leading spaces, a plurality of spaces between words public String reverseWords ( String S) { IF (S == null || s.length () == 0 ) return "" ; // a space or a plurality of spaces Split String [] = S STRs. TRIM (). Split ( "\ S +" ); the StringBuilder SB = new new the StringBuilder (); for ( int I = strs.length - . 1 ; I> 0 ; i--) { SB. the append (STRs [I] + "" ); |
Another way is to reverse traversal strings, two pointers to track the beginning and end of words, when we begin to traverse the words, the words append to the result. code show as below:
1 |
public class Solution { public String (S String) { IF (s.length S == null || () == 0 ) return "" ; the StringBuilder SB = new new the StringBuilder (); // J string pointer initially points to the last the next position of the character, in each iteration j a point on the space traversed int large column [LeetCode] Reverse Words in the I II a String > j = s.length (); for ( int I = s.length () - . 1 ; I> = 0 ; I -) { // spaces traversed, j is updated to point, point to the new space IF (s.charAt (I) == '' ) { j = I; } the else |
Reverse Words in a String II
Title Description
Similar to Question [Reverse Words in a String], but with the following constraints:
“The input string does not contain leading or trailing spaces and the words are always separated by a single space.”
Could you do it in-place without allocating extra space?
Code
1 |
// the entire string inverted and inverted word each public void ( char [] S) { Reverse (S, 0 , s.length - . 1 ); // J per word start point for ( int I = 0 , J = 0 ; I <s.length; I ++) { IF (I s.length == - . 1 || S [I] == '' ) { Reverse (S, J, I); J = I + . 1 ; } } } |