JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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?

Code

class Solution {
    public void reverseWords(char[] str) {
        if(str == null || str.length <= 1) return;
        reverse(str, 0, str.length - 1);

        int index = 0;
        int start = 0;
        // 注意处理最后一个
        while(index <= str.length){
            if(index == str.length || str[index] == ' '){
                reverse(str, start, index - 1);
                start = index + 1;
            }

            index++;
        }
    }

    private void reverse(char[] str, int start, int end){
        while(start < end){
            char temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
}