这道题目如果要理逻辑其实还挺麻烦的,所以打算好好理理这道题目
(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效果更差,就不表了。