【某书笔试算法题】python-字符串段式回文分割(段式回文字符串分割)

  回文字符串分割是一道很经典的算法题(例如,LeetCode 131),在网上也已经有了很多解法。但是,今天在某书的笔试中碰到了一种新的说法——“段式回文”。“段式回文”,其最小的单位可以是多个字母,而不仅仅是单个字母。例如,在一般的回文字符串定义中,“ana”、“oto”和“bpb”符合回文字符串,而“gotogo”不符合。然而,“gotogo”可以拆解成“go”、“to”和“go”三段,其符合“段式回文”!
  因此,在要求子串符合段式回文的情况下,“gotogo”一共有6种分割方案,分别是[g,o,t,o,g,o]、[g,o,t,ogo]、[g,oto,g,o]、[g,otogo]、[gotog,o]和[gotogo]。比较容易困惑的是“otogo”,其可拆解成“o”、“tog”和“o”,所以也属于符合段式回文的子串。
  在给定任意一个由小写英文字母组成的字符串s,如果要求分割成符合段式回文的子串,一共会有多少种可能呢?下面给出我的code:

def huiwen(s, num):
    all_hui_substring = hui_substring(s)
    top_hui_substring = []
    for tmp_hui_substring in all_hui_substring:
        if s.find(tmp_hui_substring)==0:
            top_hui_substring.append(tmp_hui_substring)
    for tmp_top_hui_substring in top_hui_substring:
        if tmp_top_hui_substring==s:
            num+=1
        else:
            num+=huiwen(s[len(tmp_top_hui_substring):], 0)
    return num

# 返回所有可能的符合段式回文的子串
def hui_substring(s):
    all_hui_substring = []
    tmp_len = len(s)
    for tmp_i in range(tmp_len):
        all_hui_substring.append(s[tmp_i])
        for tmp_j in range(tmp_i+1, tmp_len+1):
            tmp_string = s[tmp_i:tmp_j]
            if ishuiwen(tmp_string):
                all_hui_substring.append(tmp_string)
    all_hui_substring = list(set(all_hui_substring))
    return all_hui_substring

# 判断子串是否符合段式回文
def ishuiwen(s):
    tmp_len = len(s)
    center_idx = tmp_len//2
    for tmp_idx in range(center_idx):
        if s[:tmp_idx+1]==s[-(tmp_idx+1):]:
            return True
        else:
            continue
    return False

print(huiwen('gotogo', 0))
上一篇:JS字符串属性和方法


下一篇:8.18Go语言之字符串