matlab cody学习笔记 day16

这道题目如果要理逻辑其实还挺麻烦的,所以打算好好理理这道题目

(1)Find the longest sequence of 1's in a binary sequence.

Given a string such as

s = '011110010000000100010111'

find the length of the longest string of consecutive 1's. In this example, the answer would be 4.

Example:

Input x = '110100111'

Output y is 3

 

答:

function y = lengthOnes(x)
cnt=0;
a=[];
L=strlength(x);
for i=1:L
if x(i)=='1'
cnt=cnt+1;
else
cnt=0;
end
a(i)=cnt;
end
[y,index]=max(a);
end

当第i个元素为1时,计数+1,当下一个为0时,将计数归零,然后统计每一步的计数值,得到计数值的矩阵,求计数值的矩阵即可得到最终的结果。一开始我本来还觉得要加一个判断,判断下一个是否为0,如果是的话就重新计数,在0/1的情况下其实可以不用再加一个判断。

答:

function y = lengthOnes(x)

a = [];

idx = [1,find(x=='0') + 1,length(x)+2];

le = length(idx);

a(1:le-1) = idx(2:le)-idx(1:le-1)-1;

y = max(a);

用find效果更差,就不表了。

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值