|
30鱼币
今天的题目:
给定一个字符串,返回字符串的非空不同子串的个数。
示例 1:
输入:"abc"
输出:7
解释:7 个不同的子序列分别是 "a", "b", "c", "ab", "ac", "bc", 以及 "abc"。 示例 2:
输入:"aba"
输出:6
解释:6 个不同的子序列分别是 "a", "b", "ab", "ba", "aa" 以及 "aba"。 示例 3:
输入:"aaa"
输出:3
解释:3 个不同的子序列分别是 "a", "aa" 以及 "aaa"。
 欢迎大家一起答题! 
本帖最后由 TJBEST 于 2020-2-26 15:34 编辑
先写一个可能会超时的,递归的,后面再想想别的方法优化
- def fun337(string):#数学计算法
- def inner(index):
- if len(set(string[index:])) == M - index:
- return 2**(M - index - 1)
- else:
- result = 1
- for eachNum in dictionary:
- for inner_index in dictionary[eachNum]:
- if inner_index > index:
- if inner_index in resultDict:
- result += resultDict[inner_index]
- else:
- temp = inner(inner_index)
- result += temp
- resultDict[inner_index]=temp
- break
- return result
-
-
- dictionary = {}
- resultDict = {}
- M = len(string)
- for index in range(0,M):
- try:
- dictionary[string[index]].append(index)
- except Exception:
- dictionary[string[index]] = [index]
- result = 0
- if len(set(string)) == M:
- result += 2**M - 1
- else:
- for eachNum in dictionary:
- if dictionary[eachNum][0] in resultDict:
- result += resultDict[dictionary[eachNum][0]]
- else:
- temp = inner(dictionary[eachNum][0])
- result += temp
- resultDict[dictionary[eachNum][0]]=temp
- return result
复制代码
|
最佳答案
查看完整内容
先写一个可能会超时的,递归的,后面再想想别的方法优化
评分
-
查看全部评分
|