题解 | #abb#
abb
https://www.nowcoder.com/practice/0a8bbf8b9b5b4280957849ef4f240f07
n = int(input())
s = input()
#回溯
# result = []
# path = []
# def back(s):
# if len(path) == 3 and path[0]!=path[1] and path[1] == path[2]:
# # print(path)
# result.append(path.copy())
# return
# if len(path)>=3:
# return
# for i in range(len(s)):
# if path == [] or path[0] != s[i]:
# path.append(s[i])
# back(s[i+1:])
# path.pop()
# back(s)
# print(len(result))
#数学方法
D = {}
for i in s:
if i not in D:
D[i] = 1
else:
D[i] += 1
result = 0
for i in range(len(s)):
D[s[i]] -= 1 #扫描一个,向后走一个,把走过的在字典中减一
for j in D:
if j!=s[i]: #确保后面的和第一个是不同的字母
result += (D[j] * (D[j] -1) ) //2
print(result)
回溯法过了8/11,效率较低
数学用后缀和的方式进行,全部通过
