一道简答的dfs题
题目描述
对于一个字符串 S,我们定义 S 的分值 f(S)为 S 中恰好出现一次的字符个数。例如 f(“aba”) = 1,f(“abc”) = 3, f(“aaa”) = 0。
现在给定一个字符串 S0⋯n−1(长度为 n,1≤n≤10^5,请你计算对于所有 SS 的非空子串 Si⋯j(0≤i≤j<n),f(Si⋯j) 的和是多少。
输入描述
输入一行包含一个由小写字母组成的字符串 S。
输出描述
输出一个整数表示答案。
输入输出样例
输入
ababc
输出
21
思路
深度搜索找到所有的子串,要求出题目的正确答案还要排序,比如“acc”和“cac”算一种
代码
father=input()
sons=[]
nums=0
def son(s):
d=dict()
for i in range(len(s)):
if s[i] in d:
d[s[i]]+=1
else:
d[s[i]]=1
nums=0
for i in d.keys():
if d[i]==1:
nums+=1
return nums
def con(father):
global sons,nums
nums+=son(father)
for i in range(len(father)):
if i==0:
temp=father[1:]
else:
temp=father[0:i]+father[i+1:]
temp=list(temp)
temp.sort()
temp=''.join(temp)
if temp not in sons and len(temp)>=1:
sons.append(temp)
con(temp)
else:
continue
con(father)
print(nums)
编码不易,有帮助的话点个赞支持一下吧~~~