Reverse Words in a String

来源:互联网 发布:淘宝卖点卡 编辑:程序博客网 时间:2024/05/17 01:51

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

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

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


原题地址Reverse words in a string

class Solution {public:void reverseWords(string &s) {stack<string> strstack;int start = 0;int length = s.length();string str;while ( (start < length)  && (s.at(start) == ' ')) //去掉头部的空格{start++;}for (int i = start; i < length; ){if (s.at(i) != ' '){i++;}else{str = s.substr(start,i-start);strstack.push(str);while ( (i < length)  && (s.at(i) == ' '))//去掉单词之间的多个空格{i++;}start = i;}}if (length != start)//防止尾部出现空格{strstack.push(s.substr(start,length-start));}s = "";while (!strstack.empty()){s =  s+ strstack.top();strstack.pop();if (!strstack.empty()){s = s + " ";}}}};



0 0
原创粉丝点击