returning the longest substring of consecutive '1'

1 view (last 30 days)
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

Accepted Answer

David Barry
David Barry on 13 Dec 2016
Get the largest:
sSplit = strsplit(s, '0');
y = max(cellfun(@numel, sSplit));
Now get the equivalent string:
largest = repmat('1', 1, y);

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!