Advertisement
hoanmalai

Gaint and Sifat

Nov 17th, 2021
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. 4
  2. axbyczd
  3. abc
  4. --> 0
  5.  
  6. abcabcabcabc
  7. abc
  8. --> 4
  9. Vị trí: 0, 3, 6, 9
  10.  
  11. aabacbaabbaaz
  12. aab
  13. --> 2
  14. Vị trí: 0, 6
  15.  
  16. aaaaaa
  17. aa
  18. --> 5
  19. Vị trí: 0, 1, 2, 3, 4
  20.  
  21. B1: Nhập dữ liệu
  22.  
  23. B2: Loại bỏ kí tự space
  24.  
  25. B3: KMP để đếm số lần xuất hiện của s trong S
  26.  
  27. B4: Xuất kết quả
  28.  
  29. ==================================
  30. Code:
  31.  
  32. function KMPPreprocess(p):
  33. m = len(p)
  34. prefix = [0] * m
  35. i = 1
  36. j = 0
  37. while i < m:
  38. if p[i] == p[j]:
  39. j += 1
  40. prefix[i] = j
  41. i += 1
  42. else:
  43. if j != 0:
  44. j = prefix[j-1]
  45. else:
  46. prefix[i] = 0
  47. i+=1
  48. return prefix
  49.  
  50. function KMPSearch(t, p, prefix):
  51. n, m = len(t), len(p)
  52. i = j = 0
  53. res = 0
  54. while i < n:
  55. if t[i] == p[j]:
  56. i += 1
  57. j += 1
  58. if j == m:
  59. res += 1
  60. j = prefix[j - 1]
  61. elif i < n and t[i] != p[j]:
  62. if j != 0:
  63. j = prefix[j - 1]
  64. else:
  65. i += 1
  66. return res
  67.  
  68. function main:
  69. read(T)
  70. for tc = 1 to T:
  71. readLine(S)
  72. readLine(s)
  73. S.replace(' ', '');
  74. s.replace(' ', '');
  75. prefix = KMPPreprocess(s)
  76. answer = KMPSearch(S, s, prefix)
  77. print("Case " + tc + ": " + answer);
  78.  
  79. Độ phức tạp: O(T * (|S| + |s|))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement