题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
例如输入“i am a student.”,则输出“student. a am i”
代码:
解法一:首先翻转句子中的每个单词,然后再翻转整个句子,即可得到结果。
#include<iostream>
#include<string>
using namespace std;
void reverseWord(string &a,int beg,int end)
{
char tmp;
while(beg<end)
{
tmp=a[beg];
a[beg]=a[end];
a[end]=tmp;
beg++;
end--;
}
}
void reverseString(string &a)
{
int length=a.length();
int beg=0,end=0;
for(int i=0;i!=length;i++)
{
if(a.at(i)==' ')//主要是判断每个单词的开始位置和终止位置
{
end=i-1;
reverseWord(a,beg,end);
beg=i+1;
}
}
end=length-1;
reverseWord(a,beg,end);
reverseWord(a,0,length-1);//翻转整个句子
}
int main()
{
string s="i am a student.";
reverseString(s);
cout<<s;
cout<<endl;
return 0;
}
解法二:运用入栈和出栈知识实现翻转,首先把所有单词入栈,然后逐个弹出最后一个栈元素
代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<string> result;
void reverseString(string &a)
{
int length=a.length();
int count=0;
string tmp;
int i=0;
for(;i!=length;i++)
{
if(a[i]==' ')
{
tmp=a.substr(count,i-count);
count=i+1;
result.push_back(tmp);
tmp.clear();
result.push_back(" ");
}
}
result.push_back(a.substr(count,i));
}
int main()
{
string s="i am a student.";
reverseString(s);
while(!result.empty())
{
cout<<*(result.end()-1);
result.pop_back();
}
cout<<endl;
return 0;
}