LeetCode – 186. Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = “the sky is blue“,
return “blue is sky the“.

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

这道题和Rotate Arrayhttps://blog.jing.do/4727 )是一个解法。

public class Solution {
    public void reverseWords(char[] s) {
        rev(s,0,s.length-1);
        int pos = 0;
        for(int i =0;i<s.length-1;i++){
            if(s[i] == ' '){
                rev(s,pos,i-1);
                pos = i+1;
            }
        }
        rev(s,pos,s.length-1);
    }
    public void rev(char[] s,int start,int end){
        while(start<end){
            char temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start ++;
            end --;
        }
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。