2012 google校园招聘 笔试2.2

题目描述:

给定字符串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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值