- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLongestDuplicatedSubStr.py
More file actions
Latest commit
43 lines (40 loc) · 1.42 KB
/
Copy pathLongestDuplicatedSubStr.py
File metadata and controls
43 lines (40 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# given an input file of text, find the longest duplicated subsstring of characters in it.
# for example, 'Ask not what your country can do for you, but what you can do for your country'
# the longest duplicated substring is 'can do for you' then 'your country'
# build suffix array based on the string
defSuffixArr(string):
suffixArr= []
i=0
whilei<len(string) :
suffixArr.append(string[i:])
i+=1
returnsuffixArr
# only start from the beginning of the two strings,
# return the length that its two parameter strings have in common
defComLen(string1, string2):
commonLenth=0
minLen=min(len(string1),len(string2))
foriinrange(minLen):
ifstring1[i] ==string2[i]:
commonLenth+=1
else:
break
returncommonLenth
# build the suffix substring based on the given string then sort them
# compare the adjacent substrings in the array
# find the longest common length of two adjacent substrings
defLongestDupSubStr(string):
arr=SuffixArr(string)
arr.sort()
# scan through the array comparing adjacent elements
# to find the longest repeated string
printarr
maxLen=ComLen(arr[0],arr[1])
maxi=0
foriinrange(1,len(arr)-1 ):
ifComLen(arr[i],arr[i+1]) >maxLen:
maxLen=ComLen(arr[i],arr[i+1])
maxi=i
printmaxLen
returnarr[maxi][0:maxLen]
printLongestDupSubStr('Ask not what your country can do for you, but what you can do for your country')