557. Reverse Words in a String III

时间:2021-09-23 15:47:40
 1 public class ReverseWords {
 2     /**
 3      * 557. Reverse Words in a String III
 4      * Easy
 5      * <p>
 6      * 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.
 7      * <p>
 8      * Example 1:
 9      * Input: "Let's take LeetCode contest"
10      * Output: "s'teL ekat edoCteeL tsetnoc"
11      * Note: In the string, each word is separated by single space and there will not be any extra space in the string.
12      */
13     public String reverseWords(String s) {
14         String[] sb = s.split(" ");
15         String res = "";
16         for (String s1 : sb) {
17             res += new StringBuffer(s1).reverse().toString() + " ";
18         }
19         return res.substring(0, res.length() - 1);
20     }
21 
22     public String reverseWords2(String s) {
23         char[] sarr = s.toCharArray();
24         for (int i = 0; i < sarr.length; ) {
25             if (sarr[i] != ' '){
26                 int j = i;
27                 while (j+1<sarr.length && sarr[j+1]!=' ') j++;
28                 swap(sarr, i, j);
29                 i = j;
30             }else{
31                 i++;
32             }
33         }
34         return new String(sarr);
35     }
36     private void swap(char[] arr, int i, int j){
37         for (; i < j; i++, j--) {
38             char tmp = arr[i];
39             arr[i] = arr[j];
40             arr[j] = tmp;
41         }
42     }
43 }