Check if string is repetition of an unknown substring

前端 未结 2 1082
星月不相逢
星月不相逢 2021-01-27 04:46

I\'m trying to write a regex or Ruby method which will find the longest repeated pattern in a string. For example:

\"abcabc\"  => \"abc\"  
\"cccc\" => \"c         


        
2条回答
  •  -上瘾入骨i
    2021-01-27 05:20

    I knew it couldn't be that complicated, so I thought it over and found a solution:

    def unrepeat(str)
      n = str.size
    
      newstr = str
      n.times do |i|
         newstr = newstr[-1] + newstr[0..-2]
         if newstr == str
            return i + 1
         end
      end
    end
    

    This will return the length of the repeated pattern. It finds this by generating rotations of the string.

提交回复
热议问题