[LeetCode]Reverse Words in a String I II

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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] + "" );











}
sb.append(strs[0]);
return sb.toString();
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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










IF (i == 0 || s.charAt (i - . 1 ) == '' ) { // the charAt (i -. 1) == '' described the current i to the beginning of a word, the word can be obtained IF (! sb.length () = 0 ) { sb.append ( "" ); } sb.append (s.substring (I, J)); } // otherwise skip } return sb.toString (); } }











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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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 ;            }        }    }











public void reverse(char[] s, int start, int end){
while(start < end){
char temp = s[end];
s[end] = s[start];
s[start] = temp;
}
}

Guess you like

Origin www.cnblogs.com/dajunjun/p/11713120.html