HappyLeetcode1 Reverse Words in a String

來源:互聯網
上載者:User

標籤:io   ar   os   sp   for   on   bs   代碼   ad   

HappyLeetcode1:Reverse Words in a String題目描述:

 

題目思考:
  1. 建立一個數組,每個數組儲存一個單詞。
  2. 將該數組倒序輸出,每輸出一個單詞後,緊跟著輸出一個空格。
題目解題代碼Python

class Solution:

    # @param s, a string

    # @return a string

    def reverseWords(self, s):

        slist=[]

        slist=s.split()

        for i in range(len(slist)/2):

                 slist[i],slist[len(slist)-1-i]=slist[len(slist)-1-i],slist[i]

         return ‘ ‘.join(slist)

C++

class Solution {

public:

    void reverseWords(string &s) {

        if(s.empty())

            return;

       

        //remove heading and trailing spaces

        int i = 0;

        while(i<s.size() && s[i] == ‘ ‘)

            i++;

        if(i == s.size())

        {

            s = "";

            return;

        }

        int j = s.size() - 1;

        while(j>=0 && s[j] == ‘ ‘)

            j--;

        if(j == -1)

        {

            s = "";

            return;

        }

       

        s = s.substr(i,j - i + 1);

       

        size_t pos = 0;

        vector<string> strs;

        size_t begin = 0;

        while(begin < s.size())

        {

            pos = s.find_first_of(‘ ‘,begin);

            if(pos == begin)

            {

                begin++;

                continue;

            }

            else if(pos != -1)

                strs.push_back(s.substr(begin,pos - begin));

            else  //pos == -1, the end

            {

                strs.push_back(s.substr(begin,s.size() - 1 - begin + 1));

                break;

            }

            begin = pos + 1;

        }

       

        string ans;

        for(int i = strs.size() - 1; i > 0; i--)

        {

            ans += strs[i];

            ans += " ";

        }

        ans += strs[0];

        

        s = ans;

    }

};

題後總結
  1. ‘ ‘.join(slist) 堪稱列錶轉字串的神表達。
官網答案

One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.

We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.

 

HappyLeetcode1 Reverse Words in a String

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.