华为机试:在字符串中找出连续最长的数字串(含“+-”号)

题目来源

题目描述

在这里插入图片描述

题目解析

分析

在这里插入图片描述

#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;

#define needDebug false;

//比如:11.22222.333333

//合法:12、+001、-1.1
//非法:++1、+.1、1.、-00.
// 考虑以nums[i]作为结尾时的合法字符串
//  11+233.984

/*
 * 思路:先搞出可能有哪些索引可以作为起点和终点
 *  - 当str[i]是数字,但str[i - 1]不是数字时,它是起点,也可以作为终点
 *  - 有两个需要特殊处理的:
 *      str[0]如果是数字,那么加入0
 *      str[N - 1]如果是数字,
 *
 * */

std::string process(std::string line){
    if(line.empty()){
        return "";
    }
    std::vector<int> data;
    if(isdigit(line[0])){
        data.push_back(0);
    }
    for (int i = 1; i < line.size(); ++i) {
        if(isdigit(line[i]) ^ isdigit(line[i - 1])){
            data.push_back(i);
        }
    }

    if(isdigit(line.size() - 1)){
        data.push_back(line.size());
    }

    std::string ans;
    for (int i = 0; i < data.size() / 2; ++i) {
        int start = data[i * 2];
        int end = data[i * 2 + 1];
        if(start != 0){
            if(line[start - 1] == '+' || line[start - 1] == '-'){
                start = start - 1;
            }
        }
        if(end < line.size() && line[end] == '.' && (i + 1) * 2 < data.size() && data[(i + 1) * 2] == end + 1){
            end = data[(i + 1) * 2 + 1];
        }

        if(ans.size() <= end - start){
            ans = line.substr(start, end - start);
        }

    }

    return ans;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
字符串重新排列是一道比较基础的编程问题,主要考察对字符串的基本操作以及算法思维的理解。实现的思路可以分为以下几个步骤: 1. 统计字符串每个字符现的次数,可以用一个数组来记录。如果字符串有多个相同的字符,数组对应的元素值需要加上相应的次数。 2. 根据每个字符现的次数,生成一个新的字符串。比如说原字符串为"hello",那么新字符串的可能是"eolh"。这里需要注意的是,新字符串相同的字符的顺序需要和原字符串相同。 3. 需要考虑特殊情况,即原字符串有空格或者特殊字符等,需要排除这些字符。 最后,我们来看一下具体的代码实现: ```js function rearrangeString(str) { // 统计每个字符现的次数 const count = {}; for (let i = 0; i < str.length; i++) { const char = str[i]; if (/\w/.test(char)) { if (!count[char]) { count[char] = 1; } else { count[char]++; } } } // 生成新的字符串 let newStr = ''; Object.keys(count).sort((a, b) => count[b] - count[a]).forEach((char) => { newStr += char.repeat(count[char]); }); return newStr; } ``` 代码,我们首先定义一个count对象用来存储每个字符现的次数。对于字符串的每个字符,我们使用正则表达式/\w/来判断是否为字母或数字,如果是再进行统计。统计完成后,我们使用Object.keys(count)来获取count对象的键组成的数组,再使用数组的sort方法来排序,使现次数多的字符排在前面。最后,我们遍历排序后的数组,根据记录的现次数,使用字符串的repeat方法来生成新字符串

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值