【发布时间】:2016-02-17 06:12:41
【问题描述】:
我的代码有效,我正在寻找更聪明的想法以提高效率?
对于字符串相似度,定义为最长公共前缀长度, 例如,“abc”和“abd”为 2,“aaa”和“aaab”为 3。
问题是计算字符串 S 及其所有后缀的相似度, 包括它自己作为第一个后缀。
例如,对于 S="ababaa",后缀为 "ababaa"、"babaa"、"abaa"、"baa"、"aa" 和“a”,相似度为6+0+3+0+1+1=11
# Complete the function below.
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children=defaultdict(TrieNode)
self.isEnd=False
class TrieTree:
def __init__(self):
self.root=TrieNode()
def insert(self, word):
node = self.root
for w in word:
node = node.children[w]
node.isEnd = True
def search(self, word):
node = self.root
count = 0
for w in word:
node = node.children.get(w)
if not node:
break
else:
count += 1
return count
def StringSimilarity(inputs):
resultFormat=[]
for word in inputs:
# build Trie tree
index = TrieTree()
index.insert(word)
result = 0
# search for suffix
for i in range(len(word)):
result += index.search(word[i:])
print result
resultFormat.append(result)
return resultFormat
【问题讨论】:
-
我觉得你的问题更适合codereview.stackexchange.com
-
Andrea 是对的,不过,我建议this。
-
@Rockybilly,我认为编辑距离与我的要求不同?我只需要检查前缀。谢谢。
-
我建议您稍微更改措辞以使用“子字符串”而不是“后缀”,因为后缀仅表示单词的开头,而子字符串表示可以显示的字符串的较小部分字符串中的任意位置
-
@Rockybilly - 我认为这只是一个带有人为字符串相似性的编码挑战:hackerrank