当前位置:   article > 正文

Leetcode 1071. Greatest Common Divisor of Strings [Python]_1071. greatest common divisor of strings python

1071. greatest common divisor of strings python

开始想复杂了点。想用KMP,不过只知道基础版本的KMP能找Pattern串重复的开始位置。可以从最长Pattern的长度入手。其最长为Str2的长度(== Str2),所以可以从len(Str2)长度往回遍历。找到可以被Str1和Str2长度整除的Pattern长度,然后从Str2中截取相应长度的子串为Pattern, *分别的倍数后能否重复出Str1和Str2。

  1. class Solution:
  2. def gcdOfStrings(self, str1: str, str2: str) -> str:
  3. if len(str2) > len(str1): str1,str2 = str2,str1
  4. commlen = len(str2)
  5. for i in range(commlen, 0, -1):
  6. if len(str1) % i or len(str2) % i:
  7. continue
  8. fac1 = len(str1)//i
  9. fac2 = len(str2)//i
  10. if str2[:i]*fac1 == str1 and str2[:i]*fac2 == str2:
  11. return str2[:i]
  12. return ""

还是把KMP当作模版记下来吧,打车软件公司的面试就被问到了。。。。

  1. def kmp(self, S, P):
  2. m = len(P)
  3. n = len(S)
  4. S = ' ' + S
  5. P = ' ' + P
  6. ne = [0]*100010
  7. res = []
  8. j = 0
  9. for i in range(2, m+1):
  10. while j and P[i] != P[j+1]:
  11. j = ne[j]
  12. if P[i] == P[j+1]:
  13. j += 1
  14. ne[i] = j
  15. j = 0
  16. for i in range(1, n+1):
  17. while j and S[i] != P[j+1]:
  18. j = ne[j]
  19. if S[i] == P[j+1]:
  20. j += 1
  21. if j == m:
  22. res.append(i-j)
  23. j = ne[j]
  24. return res

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/493432
推荐阅读
相关标签
  

闽ICP备14008679号