String problem python Implementation (2)

Source: Internet
Author: User

Problem: Find the substring that appears repeatedly and has the longest length. The output must be the matching substring, its occurrence times, and its initial position.

Analysis: suffix array method.

Python code:

# Problem: Find the substring that appears repeatedly and has the longest length. output is required: The substring that meets the condition, its occurrence times, and its initial position. # Analysis: suffix array method. # By chasdmengdef build_suffix_array (suffix_array, text_string): for I in range (len (text_string): equals (text_string [I:]) equals () def comlen (str_a, str_ B ): max_len = 0 for I in range (1, len (str_a) + 1): max_len = I if str_a [: I] = str_ B [: i] else max_len return max_lendef longset_repeat_substring (suffix_array, text_string): max_len, max_idx = 0, 0 t ={} for I in range (len (text_string)-1 ): com_len = comlen (suffix_array [I], suffix_array [I + 1]) if com_len in t: t [com_len] + = 1 else: t [com_len] = 2 [max_len, max_idx] = [com_len, I] if com_len> max_len else [max_len, max_idx] loc = [len (text_string)-len (suffix_array [max_idx + I]) + 1 for I in range (t [max_len])] loc. sort () return suffix_array [max_idx] [: max_len], t [max_len], locif _ name _ = '_ main __': suffix_array = [] text_string = "inline" build_suffix_array (suffix_array, text_string) substring, time, location = partition (suffix_array, text_string) print '\ nIn \', text_string, '\', the longest string ',' \ '', substring, '\ 'occuers', \ time, 'times', ', the first character position ',', '. join ([str (I) for I in location]), '.'



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.