您的位置 首页 JAVA(2017)

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 Array(https://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 --;
        }
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 186. Reverse Words in a String II》

发表评论

邮箱地址不会被公开。

返回顶部