Skip to content

Commit 0135598

Browse files
author
caiminchao
committed
leetcode 30
1 parent 22328dc commit 0135598

File tree

1 file changed

+35
-26
lines changed

1 file changed

+35
-26
lines changed

solution.py

+35-26
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,6 @@ def letterCombinations(self, digits):
320320
:rtype: List[str]
321321
dfs实践
322322
"""
323-
324323
def _dfs(num, string, res):
325324
if num == length:
326325
res.append(string)
@@ -540,40 +539,52 @@ def findSubstring(self, s, words):
540539
:type words: List[str]
541540
:rtype: List[int]
542541
"""
543-
def _contate_string(str_list, s, s_list):
544-
if len(str_list) == 0:
545-
s_list.append(s)
546-
return
547-
else:
548-
for i in str_list:
549-
tmp = [t for t in str_list]
550-
s += i
551-
tmp.remove(i)
552-
_contate_string(tmp, s, s_list)
553-
554-
s_list = []
555-
_contate_string(words, '', s_list)
542+
if s == '':
543+
return
544+
if len(words) == 0:
545+
return
546+
wordsLen = len(words)
547+
wordLen = len(words[0])
548+
sLen = len(s)
556549
res = []
557-
for sl in s_list:
558-
if s.find(sl):
559-
res.append(s.find(sl))
550+
tmp = {}
551+
for w in words:
552+
if w not in tmp:
553+
tmp[w] = 1
554+
else:
555+
tmp[w] += 1
556+
557+
558+
for i in range(sLen-wordsLen*wordLen+1):
559+
current = {}
560+
j = 0
561+
while j <= wordsLen:
562+
word = s[i+j*wordLen:i+j*wordLen+wordLen]
563+
if word not in words:
564+
break
565+
if word not in current:
566+
current[word] = 1
567+
else:
568+
current[word] += 1
569+
if current[word] > tmp[word]:
570+
break
571+
j += 1
572+
if j == wordsLen:
573+
res.append(i)
560574

561575
return res
576+
562577
def LCS(self, s1, s2):
563578
"""
564579
计算两个字符串的最长公共子序列.
565-
566580
Parameters
567581
----------
568582
s1:字符串
569-
570583
s2:字符串
571-
572584
Returns
573585
-------
574586
B:二维Numpy数组
575587
标记函数值组成的矩阵
576-
577588
C:二维Numpy数组
578589
优化函数值组成的矩阵
579590
"""
@@ -604,16 +615,12 @@ def LCS(self, s1, s2):
604615
def struct_sequence(self, B, i, j, s1, s2):
605616
"""
606617
根据标记函数值矩阵输出最长公共子序列
607-
608618
Parameters:
609619
-----------
610620
B:二维Numpy数组
611621
标记函数值组成的矩阵
612-
613622
i,j:B矩阵中当前需要判断值的坐标
614-
615623
s1:字符串
616-
617624
s2:字符串
618625
"""
619626
if i == 0 or j == 0: # base case
@@ -628,4 +635,6 @@ def struct_sequence(self, B, i, j, s1, s2):
628635

629636

630637
if __name__ == '__main__':
631-
print Solution().findSubstring('barfoothefoobarman', ["foo", "bar"])
638+
s = "barfoothefoobarman"
639+
words = ["foo", "bar"]
640+
print Solution().findSubstring(s, words)

0 commit comments

Comments
 (0)