Leetcode#557. Reverse Words in a String III

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

题目描述:给定一个字符串,将字符串的每一个单词自身反转,而单词之间的顺序不变,如 “Let’s take LeetCode contest” -> “s’teL ekat edoCteeL tsetnoc”

解题思路:有了之前 Reverse Words in a String 的启发,这道题我们依然使用栈,更加简单。

  • 字符按顺序入栈,直到遇到空格,此时栈中元素全部出栈
  • 一直遍历到字符串末尾,执行上一步
  • 注意最后要将栈中元素全部出栈
class Solution {
public:
    string reverseWords(string s) 
    {
        stack<char> sta;
        string ans = "";
        for(int i = 0; i < s.length(); ++i)
        {
            if(s[i] != ' ')
                sta.push(s[i]);
            else
            {
                while(!sta.empty())
                {
                    ans += sta.top();
                    sta.pop();
                }
                ans += ' ';
            }
        }
         while(!sta.empty())
        {
            ans += sta.top();
            sta.pop();
        }
        return ans;
    }
};
查看评论

String类

-
  • 1970年01月01日 08:00

【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]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

【Leetcode】557. Reverse Words in a String III

思路: 用空格分割字符串,对每个子串,逆序,添加到结果数组。 public class Solution { public String reverseWords(String s) { ...
  • zhouziyu2011
  • zhouziyu2011
  • 2017-04-09 13:18:08
  • 1892

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: Python]557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while sti...
  • NXHYD
  • NXHYD
  • 2017-05-19 16:17:34
  • 1143

LeetCode 557 Reverse Words in a String III(逆转字符串)

Given a string, you need to reverse the order of characters in each word within a sentence while sti...
  • qq_26658823
  • qq_26658823
  • 2017-04-14 19:45:33
  • 477

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

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

LeetCode 557:Reverse Words in a String III (c++)

一:题目 Given a string, you need to reverse the order of characters in each word within a sentence w...
  • u010059070
  • u010059070
  • 2017-06-21 10:24:30
  • 257
    个人资料
    持之以恒
    等级:
    访问量: 3万+
    积分: 2156
    排名: 2万+