题目描述
将一个英文语句以单词为单位逆序排放,例如:“I am a boy”,逆序排放后为“boy a am I”,所有单词之间用一个空格隔开,语句中出了英文字母外,不再包含其他字符,数据范围:输入的字符串长度满足1<=n<=1000。
题目来源
略
输入描述
输入连续字符串(每个字符串长度小于等于100)
输出描述:
输出所有分割后的长度为8的新字符串
输入:
I am a boy
输出:
boy a am I
思路
将昨天逆序输出程序修改为以单词为单位入栈。
具体实现
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string str;
string temp;
char c;
int n=0;
int num=0;
cout << "请输入字符串!" << endl;
getline(cin,str);
int len = str.length();
stack<string> s;
for(int i=0;i<len;i++){
if(str[i]!=' '){
temp+=str[i];
}
if(str[i]==' '||i==len-1)
{
temp+=' ';
s.push(temp);
//cout<<temp;
temp="";
num++;
}
else{
//temp+=str[i];
}
}
for(int i=1;i<=num;i++){
cout<<s.top();
s.pop();
}
return 0;
}
时间复杂度
O(n)
小结
对空格的处理尚不完善。栈的操作时间空间复杂度尚未掌握。