求和最大子数字串

一道面试题

问题描述

输入多个字符串,求其中和最大的连续数字子串。
比如,
输入:sdff1232ds123dfs
输出:1232
因为1232的和最大

解答

解题集锦中常见的一道题,保存数字子串的起始索引,长度以及最大和,对每一个字符,如果是数字字符,判断前边子串和是否大于最大和,如果大于最大和,则用当前子串的起始索引,长度,和更新最大和;如果不是数字字符,则将当前子串的起始索引,长度,和至位。

//解题思路:
/**
 数字索引为begin,数字串长度n,数字最大和为maxsum
 临时数字索引tmp_begin,数字串长度tmp_n,临时数字最大个tmp_maxsum
按顺序读取每一个字符,如果遇到数字,如果前面为字母,tmp_begin跟新为当前索引,数字串长度tmp_n加1,tmp_maxsum+=当前数字,如果tmp_maxsum大于maxsum,则用临时的数字索引,字符串长度,最大数更新最大的值
 如果遇到字符,则tmp_begin,tmp_n,tmp_maxsum置为0
 遍历一遍,将下标为begin长为n的数字串打印出来
 **/


//
//  main.cpp
//  didi2
//
//  Created by LiLingyu on 15/10/15.
//  Copyright © 2015年 LiLingyu. All rights reserved.
//

#include <iostream>
#define MAXLEN 1000

void getmaxnum(char* a)
{
    int begin = 0;
    int n = 0;
    int maxsum = 0;

    int tmp_begin = -1;
    int tmp_n = 0;
    int tmp_maxsum = 0;

    for (int i=0; ; i++) {
        if (a[i]=='\0') {
            break;
        }
        else if(a[i]>='0'&&a[i]<='9')//num
        {
            if (tmp_begin == -1) {
                tmp_begin = i;

            }

            tmp_n++;
            tmp_maxsum += a[i]-'0';

            if (tmp_maxsum>maxsum) {
                begin = tmp_begin;
                n = tmp_n;
                maxsum = tmp_maxsum;
            }
        }
        else
        {
            tmp_begin = -1;
            tmp_n = 0;
            tmp_maxsum = 0;
        }

    }

    for (int i=begin; i<begin+n; i++) {
        printf("%c", a[i]);
    }
    printf("\n");
}

int main(int argc, const char * argv[]) {
    char a[MAXLEN];

    while (scanf("%s", a)!=EOF) {
        getmaxnum(a);
    }



    return 0;
}

下载:https://github.com/lilingyu/didi2

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值