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
- leetcode之Reverse Words in a string
- leetcode之Reverse Words in a String
- leetcode之Reverse Words in a String
- LeetCode之Reverse Words in a String
- Leetcode之Reverse Words in a String
- leetcode之Reverse Words in a String
- Leetcode之Reverse Words in a String
- LeetCode之Reverse Words in a String
- 【Leetcode】之 Reverse Words in a String
- Leetcode - string - Reverse Words in a String
- LeetCode 之 Reverse Words in a String — C 实现
- java中leetcode之Reverse Words in a String
- python:leetcode之reverse words in a string
- LeetCode之路:557. Reverse Words in a String III
- LeetCode之Reverse Words in a String III
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 根据手机号查询归属地
- CentOS 6.5上使用yum安装Apache
- 关于Moq的使用策略
- StringTokenizer类的使用 分割字符串
- error LNK2001: unresolved external symbol __imp__inet_ntoa@4问题解决
- Leetcode之Reverse Words in a String
- c# 几种常见的数据库连接
- C++ String STL
- 算法竞赛入门经典(第二版)第2章部分学习实现
- 计算未来六天的日期和星期几
- php开启.htaccess文件的功能
- LCS常用模板总结
- A == B ?
- Linux运维目前形势及未来展望