leetcode 186. Reverse Words in a String II 旋轉字元數組 ---------- java

來源:互聯網
上載者:User

標籤:cte   ati   end   could   question   想法   數組   example   art   

 

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?

 

1、剛開始的想法是找到第一個和最後一個單詞,然後交換他們兩個,但是遇到的問題是兩個單詞長度不一致的時候會很麻煩,就需要將剩餘的字串整個進行移動,麻煩,且效率很低。

 

 

2、參考了discuss,發現很其實想法很簡單,就是分兩步:第一步就是把整個字串倒過來,第二步就是再翻回來之後再把每個單詞反轉一次就好了。

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

 

 

 

 

leetcode 186. Reverse Words in a String II 旋轉字元數組 ---------- java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.