returning the longest substring of consecutive '1'
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I've got this question, but instead of returning the largest size of the substring. It should return the the largest substing (the string of that largest size). Could someone help me? it's just a practice problem for my test.
Question:
Given a string s = '011110010000000100010111', the length of the longest substring of s which contains consecutive ‘1's would be 4.
Write a function named longest_one , which accepts one input string consisting only of ‘0’ and ‘1’ characters. The function should return the size of the longest substring of consecutive ‘1’s. You are required to use the programming method (loops, conditional statements). The function should return the desired output regardless of the input string size .
My code for returning the largest size of the substring:
function y = longest_one(x) count = 0; y = 0; for i = 1:length(x) if x(i) == '1' count = count + 1; else y = max(y,count); count = 0; end end y = max(y,count); end
0 个评论
采纳的回答
David Barry
2016-12-13
Get the largest:
sSplit = strsplit(s, '0');
y = max(cellfun(@numel, sSplit));
Now get the equivalent string:
largest = repmat('1', 1, y);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!