首页 > 代码库 > LeetCode Reverse Words in a String III

LeetCode Reverse Words in a String III

原题链接在这里:https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description

题目:

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.

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.

题解:

与Reverse String II类似。原题中提到没有多余的space, 所以降低了难度.

遇到空格就把之前标记的部分reverse. 

Note: 最后一次reverse别忘了.

Time Complexity: O(n), n = s.length(). Space: O(n), char array.

AC Java:

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         int len = s.length();
 4         char [] charArr = s.toCharArray();
 5         int i = 0;
 6         for(int j = 0; j<len; j++){
 7             if(charArr[j] == ‘ ‘){
 8                 reverse(charArr, i, j-1);
 9                 i = j+1;
10             }
11         }
12         reverse(charArr, i, len-1);
13         return new String(charArr);
14     }
15     
16     private void reverse(char [] s, int i, int j){
17         while(i<j){
18             swap(s, i, j);
19             i++;
20             j--;
21         }
22     }
23     
24     private void swap(char [] s, int i, int j){
25         char temp = s[i];
26         s[i] = s[j];
27         s[j] = temp;
28     }
29 }

 

LeetCode Reverse Words in a String III