美文网首页
151. Reverse Words in a String

151. Reverse Words in a String

作者: juexin | 来源:发表于2017-01-09 19:20 被阅读0次

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--;
        }
    }
}

相关文章

网友评论

      本文标题:151. Reverse Words in a String

      本文链接:https://www.haomeiwen.com/subject/qgphbttx.html