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
".
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 length
while(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;
}