@@ -320,7 +320,6 @@ def letterCombinations(self, digits):
320
320
:rtype: List[str]
321
321
dfs实践
322
322
"""
323
-
324
323
def _dfs (num , string , res ):
325
324
if num == length :
326
325
res .append (string )
@@ -540,40 +539,52 @@ def findSubstring(self, s, words):
540
539
:type words: List[str]
541
540
:rtype: List[int]
542
541
"""
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 )
556
549
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 )
560
574
561
575
return res
576
+
562
577
def LCS (self , s1 , s2 ):
563
578
"""
564
579
计算两个字符串的最长公共子序列.
565
-
566
580
Parameters
567
581
----------
568
582
s1:字符串
569
-
570
583
s2:字符串
571
-
572
584
Returns
573
585
-------
574
586
B:二维Numpy数组
575
587
标记函数值组成的矩阵
576
-
577
588
C:二维Numpy数组
578
589
优化函数值组成的矩阵
579
590
"""
@@ -604,16 +615,12 @@ def LCS(self, s1, s2):
604
615
def struct_sequence (self , B , i , j , s1 , s2 ):
605
616
"""
606
617
根据标记函数值矩阵输出最长公共子序列
607
-
608
618
Parameters:
609
619
-----------
610
620
B:二维Numpy数组
611
621
标记函数值组成的矩阵
612
-
613
622
i,j:B矩阵中当前需要判断值的坐标
614
-
615
623
s1:字符串
616
-
617
624
s2:字符串
618
625
"""
619
626
if i == 0 or j == 0 : # base case
@@ -628,4 +635,6 @@ def struct_sequence(self, B, i, j, s1, s2):
628
635
629
636
630
637
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