Leetcode之Reverse Words in a String

来源:互联网 发布:收集附近电话号码软件 编辑:程序博客网 时间:2024/05/16 09:27

https://oj.leetcode.com/problems/reverse-words-in-a-string/

#include<iostream>using namespace std;#include<stack>#include<string>class Solution{public:void reverseWords(string &s){stack<char>s1;//翻转整个语句stack<char>s2;//翻转单词int flag=0;int num=0;int i=0;// 第一次遍历删除多余的空格/********************************/for(i=0;i<(int)s.size();i++){if(s[i]==' ' && flag==0) //处理头空格,直到遍历完所有头空格,接下来的元素才会入栈continue;else if(s[i]==' '){num++;if(num==1)// num计数,控制只有一个空格入栈s1.push(s[i]);}else{num=0;//记住 清0;flag=1;//去除头空格标志位s1.push(s[i]);}}if(!s1.empty() && s1.top()==' ') //处理尾空格s1.pop();/********************************/i=0;while(!s1.empty()){if(s1.top()==' ')//此时清空栈s2{while(!s2.empty()){s[i++]=s2.top();s2.pop();}s[i++]=' ';//空格入s2,同时s1.pop()之s1.pop();}else//s2入栈,s1出栈,直至遇到空格{s2.push(s1.top());s1.pop();}}while(!s2.empty())//记得s2清空{s[i++]=s2.top();s2.pop();}s.erase(i,s.size()-i);//将后面多余元素清除,切记不能用'\0',string不以'\0'结尾}};int main(){string s=" the sky is blue   ";Solution one;one.reverseWords(s);cout<<s;
  return 0;}


0 0
原创粉丝点击