Python implementation to find the longest length of the ECHO substring, python echo

Source: Internet
Author: User

Python implementation to find the longest length of the ECHO substring, python echo

Given a string, find its longest length of the substring. For example, if the input string is '000000' and its longest substring is '000000', 4 is returned.

The easiest way to think of is to enumerate all the substrings, and then judge whether the strings are input strings one by one, and return the longest length of the input substrings. I don't need to say that the duration of enumeration implementation is intolerable. Is there an efficient way to search for the response strings? The answer is of course yes, that is, the center extension method. Select an element as the center, and then search for the largest echo substring centered on the element. However, a new problem occurs. The length of the substring may be the base number or even number. For the substring with an even length, there is no central element. Is there a way to classify parity-length substrings into one category and use the central Extension Method in a unified manner? It is the manacher algorithm. It inserts special characters into the original string. For example, after inserting #, the original string becomes '#3 #5 #5 #3 #4 #3 #2 #1 #'. Now we can use the center extension for the new string. The radius obtained by the center extension method is the length of the substring.

Now the implementation idea has been clarified, first convert the string '20160301' ----> '#3 #5 #5 #3 #4 #3 #2 #1 #', then obtain the length of the longest echo substring centered on each element. The python implementation is as follows:

#! /Usr/bin/python #-*-coding: UTF-8-*-def max_substr (string ): s_list = [s for s in string] string = '#' + '#'. join (s_list) + '# 'max_length = 0 length = len (string) for index in range (0, length): r_length = get_length (string, index) if max_length <r_length: max_length = r_length return max_lengthdef get_length (string, index): # obtain the longest retrieval string centered on index length = 0 r _ = len (string) for I in range (1, index + 1): if index + I <r _ and string [index-I] = string [index + I]: length + = 1 else: break return lengthif _ name _ = "_ main _": result = max_substr ("35534321") print result

The function has been implemented and no bugs have been tested. But let's calm down and think about whether there is room for optimization for the current solution? According to the current solution, we have obtained the maximum echo substring of each element center in '123. When traversing to '4', we know that max_length is 4 for the longest response substring, which is 3 for the longest response substring centered on 4, it is smaller than max_length, so we do not update max_length. In other words, it is useless to calculate the maximum length of the 4-centered input string. This is what we want to optimize. Since the maximum length of a substring of an element does not exceed max_length, we do not need to calculate its longest substring, when traversing a new element, we should first judge whether the length of the string centered on it can surpass max_length. If it cannot exceed, we will continue to traverse the next element. The following are the optimized implementations:

#! /Usr/bin/python #-*-coding: UTF-8-*-def max_substr (string ): s_list = [s for s in string] string = '#' + '#'. join (s_list) + '# 'max_length = 0 length = len (string) for index in range (0, length): r_length = get_leng2( string, index, max_length) if max_length <r_length: max_length = r_length return max_lengthdef get_leng2( string, index, max_length): # obtain the longest string Based on the longest string known #1. center + maximum radius beyond the string range, return r _ = Len (string) if index + max_length> r _: return max_length #2. the maximum radius cannot be exceeded. return l_string = string [index-max_length + 1: index + 1] r_string = string [index: index + max_length] if l_string! = R_string [:-1]: return max_length #3. calculate the new maximum radius result = max_length for I in range (max_length, r _): if index-I> = 0 and index + I <r _ and string [index-I] = string [index + I]: result + = 1 else: break return result-1if _ name _ = "_ main _": result = max_substr ("35534321") print result

So how much is the speed improved? Taking the string 1000 '1' as an example, the execution time of the algorithm before optimization is 0.239018201828, the optimization is 0.0180191993713, and the speed is increased by about 10 times.

/usr/bin/python /Users/hakuippei/PycharmProjects/untitled/the_method_of_programming.py0.2390182018280.0180191993713

Here is another example:

#! Usr/bin/env python # encoding: UTF-8 ''' _ Author __: Lishui cold city function: Find the longest echo subsequence ''' def slice_window (one_str, w = 1): '''sliding window ''' res_list = [] for I in range (0, len (one_str)-w + 1): res_list.append (one_str [I: I + w]) return res_listdef is_huiwen (one_str_list): ''' enter a string list to determine whether the return sequence ''' if len (one_str_list) = 1: return True else: half = len (one_str_list)/2 if len (one_str_list) % 2 = 0: first_list = one_str_list [: half] second_list = one_str_list [half:] else: first_list = one_str_list [: half] second_list = one_str_list [half + 1:] if first_list = second_list [:-1]: return True else: return False def trim (one_str ): '''main function, find the longest echo subsequence ''' all_sub = [] for I in range (1, len (one_str): all_sub + = slice_window (one_str, I) all_sub.append (one_str) new_list = [] for one in all_sub: if is_huiwen (list (one): new_list.append (one) new_list.sort (lambda x, y: cmp (len (x ), len (y), reverse = True) print new_list [0] if _ name _ = '_ main _': one_str_list = ['uabmove baop ', 'abba', 'dmfdkgbbfdlg', 'mnfkabcbadk'] for one_str in one_str_list: find_longest_sub_palindrome_str (one_str)

The result is as follows:

abcdcba abcba bb abcba [Finished in 0.3s] 

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.