将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
输入描述:
每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100</pre>
输出描述:
依次输出倒置之后的字符串,以空格分割
示例1输入
I like beijing.
输出
beijing. like I
思路
先把字符串整体倒序,之后再将每个单词倒序,主要考验硬编码能力。
具体实现代码
#include <iostream>
#include <string>
using namespace std;
typedef long long LL;
void reverse(string &s) {
int length = s.size();
for (int i = 0; i < length / 2; i++) {
char temp = s[i];
s[i] = s[length - 1 - i];
s[length - 1 - i] = temp;
}
}
void reversed(string &s) {
reverse(s);
int length = s.size(), start = 0,end = 0;
//cout << s << endl;
bool flag = true;
for (int i = 0; i < length; i++) {
if (s[i] == ' ' && flag) {
string temp = s.substr(start, i - start );
//cout << temp << endl;
reverse(temp);
s.replace(start, i - start, temp);
flag = false;
}
else if (!flag) {
start = i;
flag = !flag;
}
}
string temp = s.substr(start, length - start);
//cout << temp << endl;
reverse(temp);
s.replace(start , length - start, temp);
}
int main() {
ios::sync_with_stdio(false);
string s;
getline(cin, s);
reversed(s);
cout << s << endl;
system("pause");
return 0;
}
我的实现有点笨,不过算是练习了一下string类的用法吧。reverse可以用库,另外substr函数也可以不用。end和start变量也属于多余。
下面是精简版的大佬写的代码!
链接:[https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355](https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355)
来源:牛客网
int main() {
string str;
while (getline(cin, str)) {
reverse(str.begin(), str.end());
int i = 0, j = i;
while (i<str.size()) {
while (i<str.size() && str[i] == ' ')
++i;
j = i;
while (i<str.size() && str[i] != ' ')
++i;
reverse(str.begin() + j, str.begin() + i);
j = i;
}
cout << str << endl;
}
return 0;
}
网友评论