Finding the shortest repetitive pattern in a string

后端 未结 4 1541
旧巷少年郎
旧巷少年郎 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:42

    This problem is a great Rorschach test for your approach to problem solving. I'll add a signal engineering solution, which should be simple since the signal is expected to be perfectly repetitive, assuming this holds: find the shortest pattern that upon repetition generates the whole string.

    In the following str fed to the function is actually a column vector of floats, not a string, the original string having been converted with str2num(str2mat(str)'):

    function res=findshortestrepel(str);
    [~,ii] = max(fft(str-mean(str)));
    res = str(1:round(numel(str)/(ii-1)));
    

    I performed a small test, comparing this to the regexp solution and found it to be faster overall (blue squares), although somewhat inconsistently, and only if you don't consider the time required to convert the string into a vector of floats (green squares). However I did not pursue this further (not breaking records with this):

    Times in sec.

提交回复
热议问题