码迷,mamicode.com
首页 > 移动开发 > 详细

HappyLeetcode1 Reverse Words in a String

时间:2014-12-13 17:49:10      阅读:219      评论:0      收藏:0      [点我收藏+]

标签: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

标签:io   ar   os   sp   for   on   bs   代码   ad   

原文地址:http://www.cnblogs.com/chengxuyuanxiaowang/p/4161531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!