Guest User

Untitled

a guest
Jun 18th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "flag"
  5. "fmt"
  6. "os"
  7. )
  8.  
  9. func makeTable(word string) ([]int) {
  10. table := make([]int, len(word))
  11. pos := 2
  12. cnd := 0 // candidate substring
  13. table[0] = -1; table[1] = 0
  14.  
  15. for pos < len(word) {
  16. if word[pos - 1] == word[cnd] {
  17. table[pos] = cnd + 1
  18. pos += 1
  19. cnd += 1
  20. } else if cnd > 0 {
  21. cnd = table[cnd]
  22. } else {
  23. table[pos] = 0
  24. pos += 1
  25. }
  26. }
  27. return table
  28. }
  29.  
  30. func search(word string, text string) int {
  31. m := 0
  32. i := 0
  33. table := makeTable(word)
  34.  
  35. for (m+i) < len(text) {
  36. if word[i] == text[i+m] {
  37. i += 1
  38. if i == len(word) {
  39. return m
  40. }
  41. } else {
  42. m = m + i - table[i]
  43. if table[i] > -1 {
  44. i = table[i]
  45. } else {
  46. i = 0
  47. }
  48. }
  49. }
  50. return -1
  51. }
  52.  
  53. func main() {
  54. flag.Parse()
  55. if (len(flag.Args()) != 2) {
  56. fmt.Fprintf(os.Stderr, "Usage: kmp WORD TEXT_TO_SEARCH_IN\n")
  57. os.Exit(1)
  58. }
  59. word := flag.Arg(0)
  60. text := flag.Arg(1)
  61. index := search(word, text)
  62. println(index)
  63. if index < 0 { os.Exit(1) } else { os.Exit(0) }
  64. }
Add Comment
Please, Sign In to add comment