151. Reverse Words in a String

Given an input string, reverse the string word by word.
For example,Given s = "the sky is blue",
return "blue is sky the".
**Update (2015-02-12):
**For C programmers: Try to solve it in-place in O(1) space.

public class Solution {
    public String reverseWords(String s) {
        int n = s.length();
    //    String rec = "";
        if(n<=0)
          return s;
        reverse(0,n-1,s);
        int p =0,q= 0;
        while(q<=n)
        {
            if(s.charAt(q)==' '||q == n)
            {
                reverse(p,q-1,s);
                p = q+1;
            }
            q++;
        }
        return s;
    }
    
    private void reverse(int start,int end,String str)
    {
        
        while(start<=end)
        {
            char temp = str.charAt(start);
            str.charAt(start) = str.charAt(end);
            str.charAt(end) = temp;
            start++;
            end--;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容