题目描述:
给定字符串s,要求把s中的连续空格压缩成一个空格,并将连续的非空字符串倒序打印出来。例如,给定 “abc def efg”, 打印“cba def gfe”。
思路,这个题看似简单,但是要写正确确实很难。
下面我给几个测试案例
(1):“***” , (2)“**abc**def” (3) "abc" (4) “abc **def**”
上面为了方便看出空格,空格用星号(*)代替
下面给出我的程序,欢迎大家批评指正。
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <cstdio>
using namespace std;
void reverse (string & str, int lhs, int rhs) {
int len = str.length();
if (lhs >= len || rhs >= len || rhs < 0 || lhs < 0)
return;
if (lhs == rhs)
return;
if (lhs > rhs)
swap (lhs, rhs);
while (lhs < rhs) {
swap (str.at(lhs++), str.at(rhs--));
}
}
void change_str (string & line) {
int i = 0;
while (i < line.length()) {
// deal space
int pre = i;
while (i < line.length() && line.at(i) == ' ') {
++i;
}
if (i - pre > 1) {
line.erase(pre, i - pre - 1);
i -= (i-pre - 1);
}
pre = i;
while (i < line.length() && line.at(i) != ' ') {
++i;
}
if (i - pre > 0 && i <= line.length())
reverse (line, pre, i-1);
}
}
int main () {
string line ;
while (getline(cin, line)) {
cout << "line : " << line << endl;
change_str (line);
cout << "change line : " << endl;
for (int i = 0, e = line.length(); i < e; ++i ) {
if (line.at(i) == ' ')
cout << "*";
else
cout << line.at(i);
}
cout << endl;
}
}