Reverse Words in a String【leetcode 1】
来源:互联网 发布:程序员年度评价 编辑:程序博客网 时间:2024/06/05 21:03
leetcode第一题,字符串反转问题:
需要注意的问题:
1.“ a "只有一个字符是或者字符串最前面有空格时,如何不输出最后那个空格?
2.字符串最后面有空格时如何解决,这个问题在做题目之前发现了,就特意注意了一下
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.
我的思路方法:
读入字符串,并得到长度,每次从最后遍历,若是空格len--;直到遇到非空格,设置一个统计变量c,来统计每个单词的长度,然后在push_back这个单词的没个字符,然后再压入一个空格,如此循环,直到len= 0;
代码带了很多cout<<来调试的
#include <iostream>#include <cstring>#include <cstring>using namespace std;void reverseWords(string &s){int len = s.size();// hello world 11//cout<<"len="<<len<<endl;string ss;while(s[len-1] == ' '){len--;// 去掉最后面的多个空格,如果有空格的话}//cout<<"len2="<<len<<endl;int c = 0;// per word lengthwhile(len > 0){while(s[len-1] == ' ' && len>0){len--;// 去掉(忽略)最后面的多个空格,如果有空格的话}while(s[len - 1] != ' ' && len>0){len--;c++;//单词的长度}//cout<<"len3= "<<len<<" c="<<c<<endl;for(int i=0;i<c;i++){ss.push_back(s[len+i]); //找到一个单词}while(s[len-1] == ' ' && len>0){len--;// 去掉(忽略)最后面的多个空格,如果有空格的话}if(len>0)ss.push_back(' ');//cout<<"ss="<<ss<<endl;c=0;}s = ss;}int main(){ string s = " a "; cout<<s<<endl; reverseWords(s);cout<<s<<endl;return 0;}
0 0
- LeetCode 1 Reverse Words in a String
- [leetcode] Reverse Words in a String [1]
- (leetcode 1)Reverse Words in a String
- LeetCode 1 Reverse Words in a String
- Reverse Words in a String【leetcode 1】
- Leetcode - string - Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- Reverse Words in a String (LeetCode)
- LeetCode Reverse Words in a String Total
- LeetCode(151)Reverse Words in a String
- Reverse Words in a String -- LeetCode
- leetcode Reverse Words in a String
- LeetCode OJ:Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [Leetcode] Reverse Words in a String
- 接下来,是脱离屌丝428天系列,
- 创建.sh脚本
- unity-Shader入门指南
- JavaScript及jQuery选择器 + DOM创建节点
- Java:精选30道Java笔试题解答
- Reverse Words in a String【leetcode 1】
- Spring的JDBCTemplate
- 数据库的一些基本知识(1)------数据库引擎
- JavaScript跨域总结与解决办法
- ASP网站架设服务器之后打开出现include file=../header.asp 这样的代码
- git 分支管理
- Python的函数参数传递
- 数组名和指针作为形参?
- 刘云山:价值观自信是保持民族精神独立性的重要支撑