【Leetcode】Reverse Words in a String II

来源:互联网 发布:mysql 博客 编辑:程序博客网 时间:2024/06/01 09:53

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?


public class Solution {    public void reverseWords(char[] s) {        int len = s.length, i , j;        reverse(s, 0, len-1);        for(i=0,j=0;j<len;j++){            if(s[j]==' '){                reverse(s,i,j-1);                i=j+1;            }        }        reverse(s, i, len - 1);    }        public void reverse(char[] s, int start, int end){        for(int i=start, j=end; i< j; i++,j--){            char tmp = s[j];            s[j] = s[i];            s[i] = tmp;        }    }}


0 0
原创粉丝点击