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--;
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容