Leetcode#151. Reverse Words in a String

0人阅读 评论(0) 收藏 举报
分类:

题目描述:将一个字符串按照单词反转,比如 “the sky is blue” -> “blue is sky the”

解题思路:借助于栈。

  • 入栈。将单词分出来,按顺序全部入栈,;
  • 出栈。单词出栈,每出一次加一个空格;
  • 最后会多一个空格,要取除了最后一个元素的子串;
class Solution {
public:
    void reverseWords(string &s) 
    {
        if(s.empty())
            return;
        stack<string> sta;
        string singleword = "";
        for(int i = 0; i < s.length(); ++i)
        {
            if(s[i] != ' ')
            {
                singleword += s[i];
            }
            else
            {
                if(singleword != "")
                    sta.push(singleword);
                singleword = "";
            }
        }
        if(singleword != "")
            sta.push(singleword);

        s = "";
        while(!sta.empty())
        {
            s += sta.top();
            sta.pop();
            s += ' ';
        }
        s = s.substr(0, s.length() - 1);
    }
};
查看评论

String类

-
  • 1970年01月01日 08:00

[leetcode] 151. Reverse Words in a String 解题报告

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reverse the s...
  • qq508618087
  • qq508618087
  • 2016-01-18 14:40:11
  • 1740

【LeetCode】Reverse Words in a String III 解题报告

【LeetCode】Reverse Words in a String III 解题报告标签(空格分隔): LeetCode题目地址:https://leetcode.com/problems/rev...
  • fuxuemingzhu
  • fuxuemingzhu
  • 2017-04-12 11:48:48
  • 1212

【LeetCode刷题Java版】Reverse Words in a String

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", r...
  • bruce_6
  • bruce_6
  • 2014-10-13 14:21:21
  • 2172

python:leetcode之reverse words in a string

要求: reverse words in a string将abc def形式的字符串翻转成def abc,并且去掉多余的空格。解法一:将abc和def分开,然后使用list的reversed方法调换...
  • justheretobe
  • justheretobe
  • 2016-02-21 17:30:27
  • 925

151. Reverse Words in a String Leetcode Python

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue"...
  • hyperbolechi
  • hyperbolechi
  • 2015-03-29 22:56:22
  • 927

[LeetCode]557. Reverse Words in a String III(反转字符串 III)

557. Reverse Words in a String IIIGiven a string, you need to reverse the order of characters in eac...
  • whl_program
  • whl_program
  • 2017-04-10 00:46:36
  • 1096

557. Reverse Words in a String III(C语言)

今天6:30起来,瞌睡了一上午,在柏宁的帮助下把这道反转的题搞出来了嘿嘿char* reverseWords(char* s) { int i=0,j=0; int start=0,e...
  • yanqueen2011
  • yanqueen2011
  • 2017-04-12 10:00:23
  • 594

(LeetCode) Reverse Words in a String

problem :Reverse Words in a String Given an input string, reverse the string word by ...
  • zhangyuehuan
  • zhangyuehuan
  • 2014-04-13 09:26:54
  • 8272

LeetCodeOJ--Reverse Words in a String(python版本)

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue"...
  • tianzhaixing
  • tianzhaixing
  • 2014-06-09 11:09:44
  • 1623
    个人资料
    持之以恒
    等级:
    访问量: 3万+
    积分: 2157
    排名: 2万+