字符串问题python实现(一)

问题:求一个字符串中连续出现次数最多的子串。

分析:后缀数组方法求解。

python版代码:

# -*- coding:utf-8 -*-
# 问题:求一个字符串中连续出现次数做多的子串.
# 分析:使用后缀数组求解
# by chasdmeng

def build_suffix_array(suffix_array, text_string):
    for i in range(len(text_string)):
        suffix_array.append(text_string[i:])
        print suffix_array[i]

def con_sub(suffix_array, text_string):
    max_time = 0
    ret_len = 0
    for i in range(1,(len(text_string)+1)/2+1):
        for j in range(len(text_string)-i):
            k=j
            temp_time = 1
            while k+i<=(len(text_string)-1) and suffix_array[k][:i] == suffix_array[k+i][:i]:
                temp_time +=1
                k +=i
            [m, ret_len, max_time] = [j, i, temp_time] if temp_time > max_time else [m, ret_len, max_time]
    return suffix_array[m][:ret_len], max_time

if __name__ == '__main__':
    suffix_array = []
    text_string = "abcbcbcabc"

    build_suffix_array(suffix_array, text_string)
    substring, time = con_sub(suffix_array, text_string)
    
    print '\n',substring, 'occuers', time, 'times'

你可能感兴趣的:(字符串,python,后缀数组)