Finding the shortest repetitive pattern in a string

后端 未结 4 1605
旧巷少年郎
旧巷少年郎 2021-01-18 05:20

I was wondering if there was a way to do pattern matching in Octave / matlab? I know Maple 10 has commands to do this but not sure what I need to do in Octave / Matlab. So

4条回答
  •  青春惊慌失措
    2021-01-18 05:45

    Another approach is as follows:

    1. determine length of string, and find all possible factors of the string length value
    2. for each possible factor length, reshape the string and check for a repeated substring

    To find all possible factors, see this solution on SO. The next step can be performed in many ways, but I implement it in a simple loop, starting with the smallest factor length.

    function repeat = repeats_in_string(str);
    ns = numel(str);
    nf = find(rem(ns, 1:ns) == 0);
    for ii=1:numel(nf)
        repeat = str(1:nf(ii));
        if all(ismember(reshape(str,nf(ii),[])',repeat)); 
            break;
        end
    end 
    

提交回复
热议问题