递归算法查找字符串中相同字符连续出现的最大次数

【百度研发工程师笔试题】递归求字符串中相同字符连续出现的最大值 用递归的方式实现一个求字符串中连续出现相同字符的最大值 阅读详情
题目:使用递归算法查找字符串中相同字符连续出现的最大次数
举例:输入“aaabbc”,输出3
分析:问题实质上是“查找字符串中相同字符连续出现的最大次数”,关键是限制了只允许使用递归的方法。
思路:1、非递归的情况:连续字符的问题可以通过设置前后指针,不断移动比较两个指针的值即可解决。
int CountMaxNumOfChar(const char *str) {
	if (str == NULL || *str == '\0') return 0;

	const char *pBefore = str;
	int max = 1;
	int cur = 1;
	while (*++pBefore) {
		if (*pBefore == *str) {
			++ cur;
			max = cur > max ? cur : max;
		}
		else {
			str = pBefore;
			cur = 1;
		}
	}
	return max;
}

2、递归的情况:递归要把问题分解成与原问题同类型的子问题,这里考虑把一个字符串的最大连续字符次数分解为求第一个字符的连续的次数,若不为当前最大,继续向后考虑子串,直到遍历全部字符串。这里需要保存第一个字符已经出现的次数和当前最大的次数。递归里面保存传递数据,可以使用参数传递,也可以考虑使用静态变量(求阶乘中有使用)。这里统计第一个字符的次数使用静态变量,保存当前最大使用参数传递。
void CountMaxNumOfCharCore(const char *str, int *max) {
	static int count = 1;
	if (*str) {
		if (*str == *(str - 1)) 
			*max = ++ count > *max ? count : *max;
		else 
			count = 1;

		CountMaxNumOfCharCore(++str, max);
	}
}

int CountMaxNumOfCharRecursive(const char *str) {
	if (str == NULL || *str == '\0') return 0;
	if (*++str == '\0') return 1;
	int max = 1;
	CountMaxNumOfCharCore(str, &max);
	return max;
}

PS:百度,2013,校招,笔试
参考:
[1]http://blog.youkuaiyun.com/zyy5411/article/details/8104493
查找字符串中出现重复次数最多的字符 查找字符串中出现重复次数最多的字符,面试中经常遇到的面试题,对找工作很有帮助,拿出来与大家一起学习进步。 立即下载

相关推荐

随机森林模型及案例(Python)

1 集成模型简介 集成学习模型使用一系列弱学习器(也称为基础模型或基模型)进行学习,并将各个弱学习器的结果进行整合,从而获得比单个学习器更好的学习效果。 集成学习模型的常见算法有Bagging算法和Boosting算法两种。 Bagging算法的典型机器学习模型为随机森林模型,而Boosting算法的典型机器学习模型则为AdaBoost、GBDT、XGBoost和LightGBM模型。 1.1 Bagging算法简介 Bagging算法的原理类似投票,每个弱学习器都有一票,最终根据所有弱学习器的投

qq_42433311的博客 4万+

华为OD机试题:连续字符最大次数

题目描述:输入一串字符串,字符串长度不超过100,查找字符串中相同字符连续出现的最大次数。 输入描述:输入只有一行,包含一个长度不超过100的字符串 输出描述:输出只有一行,输出相同字符串连续出现的最大次数 说明:字符串区分大小写 示例:1.输入:hello 输出:2 2.输入:word 输出:1 3.输入:aaabbc 输出:3...

cxh21627的博客 725

QCC308x/3095收发一体:TX/RX双模一拖二与多编码广播实战解析

本文深度解析高通QCC308x/3095蓝牙音频芯片的TX/RX双模功能与广播应用。芯片支持发射和接收模式下的“一拖二”连接,并能实现LE Audio多设备广播,显著提升多设备音频切换体验与商业广播能力,适用于健身、导览等丰富场景。

g9h0i1的博客 1003

计算字符串中最大连续相同的字符个数

3.如果当前连续字符大于max,将max的值改为count,一旦出现前后字符不相同,将count置为1然后继续循环,当循环到后一个字符是\0时代表字符串已经结束,返回max。2.需要一个max记录出现过的最大的连续相同字符个数,还需要一个count记录当前连续字符已经出现了几个。ok,理清思路,咔,很快啊,代码就写出来了。1.只要字符串有值,连续相同最少也是一个。怎么做呢,先理一下思路。大功告成,继续学习!

m0_67331304的博客 1265

CVPR2021 CenterPoint源码解读:从VoxelNet到两阶段优化的完整实现细节

本文深度解析了CVPR 2021 CenterPoint模型的完整实现细节,从VoxelNet体素化、稀疏卷积Backbone,到基于中心点的检测头与两阶段精修机制。文章提供了从环境搭建、数据预处理到核心代码模块(如热力图生成、关键点特征提取与MLP Refiner)的实战指南,并分享了训练策略、多任务损失调优及可视化调试等关键工程实践,助力开发者深入理解并复现这一高效的3D目标检测框架。

linux的博客 470

华为OD机试真题 - 矩阵匹配 牛客网

2024华为OD机试真题,代码包含语言java、js、python、c 代码基本都有详细注释。 题目描述 从一个 N * M(N ≤ M)的矩阵中选出 N 个数,任意两个数字不能在同一行或同一列,求选出来的 N 个数中第 K 大的数字的最小值是多少。 输入描述 输入矩阵要求:1 ≤ K ≤ N ≤ M ≤ 150 输入格式: N M K N*M矩阵 输出描述 N*M 的矩阵中可以选出 M! / N! 种组合数组,每个组合数组种第 K 大的数中的最小值。无需考虑重复数字,直接取字典排序结果即可。

2301_76543445的博客 498

12、字符串中连续最多的字符以及次数

要注意实际复杂度,不要被代码表面迷惑双指针常用于解决嵌套循环算法题慎用正则表达式(实际工作可以用)

天界程序员的博客 792

【C语言】计算字符串 中最大连续相同的字符个数

【代码】【C语言】计算字符串 中最大连续相同的字符个数。

weixin_43716840的博客 907

机器视觉/将HIK海康面阵相机连接Halcon软件

本文简述了如何将海康面阵相机连接到Halcon软件中进行实时取图的过程。

Dahe.qu 4866

手把手教你学Simulink——无刷直流电机(BLDC)霍尔传感器(Hall Sensor)信号处理电路仿真

在中,转子位置靠​ 给出,换相逻辑(Commutation Table)据此决定。实际霍尔输出是,且常有:比较迟滞(内置或外加分压)RC 低通(防 EMI 尖刺)与 MCU 间想让你霍尔三相 UVW 理想方波(120° each, 换相每 60°elec)经观察:原始 HU/HV/HW、滤波后波形、整形后 TTL 电平验证换相表(001→100→010…)与转子转向匹配是破局关键。

amy_mhd的博客 38

寻找字符串中,连续重复次数最多的字符

比如有一个字符串: ‘aaaabbbbbcccccccccccccdddddd’ 这里边连续重复出现次数最多的是 c 共出现了 13 次,我们要想办法使用js找出来 解题思想:同时声明两个指针,i 和 j,初始值都是 0 同时指向下标为 0 的位置,遍历字符串,i停在 0 位, j 往后走,每走一次和 i 指针指向的位置做比较,如果相同,什么也不做,如果不同,就说明连续重复出现 的字符串结束了,i — j 指针之间的字符串就是相同的,j - i 就是出现的次数 这时候判断 j - i 是否大于 maxR

泥猴桃的博客 5142

动量因子在A股市场的有效性分析:量化实证研究

验证动量因子在A股市场的有效性及时间周期性分析不同时间窗口(短期/中期/长期)对动量效应的影响量化交易成本、市场流动性对动量策略收益的侵蚀程度比较A股与成熟市场(如美股)动量效应的差异特征理论框架:行为金融学解释动量效应的产生机制技术实现:Python全流程代码实现动量因子计算与回测实证分析:统计检验、风险收益指标、敏感性分析应用拓展:结合市场微观结构的策略优化方案动量因子(Momentum Factor)

2501_92132293的博客 2476

[2013百度软件研发笔试题] 求字符串中连续出现相同字符的最大值

题目完整描述为:用递归的方式实现一个求字符串中连续出现相同字符的最大值,如aaabbcc,连续出现a的最大值为3,abbc,连续出现字符最大的值为2。 以下是我想出来的方法: #include using namespace std; #define MAX(a, b) (a) > (b) ? (a) : (b) int Get(char *s, int n, int m) /

Miracles happen every day. 7207

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

用递归实现查找字符串中相同字符连续出现次数的最大值

// recursive.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include using namespace std;//char szGame[]={w,w,k,k,k,k,l,l,l,m,m,m};c

ArduousBonze的专栏 3847

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

字节青训-比赛配对问题 、组成字符串ku的最大次数

支队伍开始,直到决出唯一获胜队伍为止,总共进行的配对次数。每次配对都会减少队伍的数量,直到只剩下一个队伍。小R想知道在比赛中进行的配对次数,直到决出唯一的获胜队伍为止。小R正在组织一个比赛,比赛中有。

像污秽一样的博客 1422

字符串的最大子串问题

基于字符串的最大子串问题是经常面试的问题,想要表现的好不但要会基础的方法,同时还要学会优化的算法。 常考的有两个问题: 1:两个字符串的最大公共子串(还可能是子序列) 2:同一个字符串中相同的最大子串问题 例如输入qweabcuwabcfw,输出结果为:重复字符串的长度3和位置4 一:求两个字符串的最大公共子串 #include&lt;iostream&gt; #...

runner668的博客 1万+

获取两个字符串中最大相同子串的实现

/** * 获取两个字符串中最大相同子串。第一个动作:将短的那个串进行长度一次递减的子串打印。 * "abcwerthelloyuiodef" * "dvhellobnm" * 思路: * 1,将短的那个子串按照长度递减的方式获取到 * 2,将没获取到的子串去长串中判断是否包含, * 如果包含,已经找到!。 */ @Test public

jzpkzm的专栏 3846

Java练习之 获取两个字符串中最大相同子串

import org.junit.Test; import java.util.Arrays; /** * @author 大跳蚤 * @create 2020/11/29 * @describe 获取两个字符串中最大相同子串。比如: str1 = "abcwerthelloyuiodefabcdef";str2 = "cvhellobnm" 提示:将短的那个串进行长度依次递减的子串与较长的串比较。 */ public class StringDemo2 { //前

qq_45922060的博客 529

递归算法计算一个字符串中最大的连续字符个数

用递归算法计算一个字符串中最大的连续字符个数。  比如 aaabbcc 输出 3, aabbcc 输出 2,abc 输出 1  class BaiduTest { public static void main(String args[]) { System.out.println(test(0, "dasdhskjaaaauenduejsdleifnchfjfkkaaaafg"))

刘尚伟 1813

用递归算法计算一个字符串中最大的连续字符个数

题目大意:用递归算法计算一个字符串中最大的连续字符个数,比如aabbcc输出3,aabbcc输出2,abc输出1 思路:递归:当前和一个比较,相同就count+1,并更新max的值,不同就把count置1。调用本身:当前位置+1。 代码: #include #include using namespace std; int JJ(string str, int cur, i

lanximu的专栏 2084

算法:如何统计字符串中连续的重复字符个数

1.用递归的方法实现一个求字符串中连续出现相同字符的最多次数,例如‘a aabbcc’中连续出现‘a‘的次数为3,‘b’为2 2.代码如下: def getMaxDuppChar(s,startIndex,curMaxLen,maxLen): if startIndex == len(s)-1: return max(curMaxLen,maxLen) if list(s)[startIndex] == list(s)[startIndex + 1]: re

weixin_43697214的博客 3932

2013百度笔试 求字符串中连续出现相同字符的最大值

题目完整描述为:用递归的方式实现一个求字符串中连续出现相同字符的最大值,如aaabbcc,连续出现a的最大值为3,abbc,连续出现字符最大的值为2。

oqqNAME的专栏 1023

字符串删除游戏的最大操作数:从生活到算法的思维之旅

给定字符串s,我们定义函数f(s)为删除s所需的最大操作数。操作规则如下:直接删除整个字符串(计为1次操作)若存在i(1 ≤ i ≤ |s|/2),使得s[0:i] = s[i:2i],则可删除前i个字符,然后对剩余字符串继续操作目标:计算f(s)的最大可能值。

司徒鸿的博客 2163
上一篇: N个结点可构成多少不同的二叉树
下一篇: 有关复制构造函数的改错
rainyi2007
博客等级 码龄17年 16粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值