Reverse Words in a String

简介: Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the".

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
提交了好多遍,终于成功了,使用了sstream来分割字符串,使用栈来存放分割之后的字符串,然后出栈就是逆序了。。
 
C++实现代码:
#include<iostream>
#include<string>
#include<sstream>
#include<stack>
using namespace std;

class Solution
{
public:
    void reverseWords(string &s)
    {
        if(s.empty())
            return;
        stringstream ss(s);
        s.clear();
        stack<string> st;
        string tmp;
        while(ss>>tmp)
        {
            st.push(tmp);
        }
        while(!st.empty())
        {
            tmp=st.top();
            st.pop();
            if(!st.empty())
                s+=tmp+' ';
            else
                s+=tmp;
        }
    }
};

int main()
{
    Solution s;
    string ss="  the   sky   is    blue  ";
    cout<<ss.length()<<endl;
    cout<<ss<<endl;
    s.reverseWords(ss);
    cout<<ss.length()<<endl;
    cout<<ss<<endl;
}

运行结果:

运行结果:

 

相关文章
|
7月前
CF1553B Reverse String(数学思维)
CF1553B Reverse String(数学思维)
23 0
|
3月前
|
Go 机器学习/深度学习 Rust
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
35 0
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
|
7月前
|
机器学习/深度学习
CF71A Way Too Long Words(string简单模拟)
CF71A Way Too Long Words(string简单模拟)
36 0
|
机器学习/深度学习 NoSQL 算法
LeetCode 344. 反转字符串 Reverse String
LeetCode 344. 反转字符串 Reverse String
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
70 0
LeetCode 344. Reverse String
LeetCode之Reverse String II
LeetCode之Reverse String II
84 0
LeetCode之Reverse String
LeetCode之Reverse String
71 0
|
Java 索引 Python
LeetCode 151:给定一个字符串,逐个翻转字符串中的每个单词 Reverse Words in a String
公众号:爱写bug(ID:icodebugs) 翻转字符串里的单词 Given an input string, reverse the string word by word. 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
1553 0
|
机器学习/深度学习 JavaScript NoSQL
Leetcode 344:Reverse String 反转字符串(python、java)
Leetcode 344:Reverse String 反转字符串 公众号:爱写bugWrite a function that reverses a string. The input string is given as an array of characters char[].
872 0
|
C++
LeetCode 344 Reverse String
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51315232 ...
706 0