LeetCode Reverse Words in a String II

时间:2023-12-17 17:08:56

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

题目:

Given an input string , reverse the string word by word.

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note:

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

Follow up: Could you do it in-place without allocating extra space?

题解:

input变成 char array.

先reverse 全部 char array. 从头往后走,遇到空格或者array尾部,就reverse中间的单词.

Note: Do NOT forget i == n, reverse.

Time Compelxity: O(s.length()). Space: O(1).

AC Java:

 public class Solution {
public void reverseWords(char[] s) {
if(s == null || s.length == 0){
return;
}
reverse(s, 0, s.length-1); int lo = 0;
for(int i = 1; i<=s.length; i++){
if(i == s.length || s[i] == ' '){
reverse(s, lo, i-1);
lo = i+1;
}
}
} private void reverse(char [] s, int i, int j){
while(i < j){
swap(s, i++, j--);
}
} private void swap(char [] s, int i , int j){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}

类似Reverse Words in a String.

跟上Reverse Words in a String IIIRotate Array.