10.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. func isMatchRegex(s string, p string) bool {
  3. // If former x chars of string matches former y chars
  4. // of pattern, match[x][y] == true, else == false
  5. var match [][]bool
  6. // Init match
  7. for i := 0; i < len(s)+1; i++ {
  8. row := make([]bool, len(p)+1)
  9. match = append(match, row)
  10. }
  11. // "" matches ""
  12. match[0][0] = true
  13. // Current & last char index of pattern
  14. currP, lastP := 1, 0
  15. for currP <= len(p) {
  16. zeroOrMore := false
  17. // Current char of pattern
  18. charP := p[currP-1]
  19. if currP < len(p) && p[currP] == '*' {
  20. zeroOrMore = true
  21. currP++ // To skip '*'
  22. match[0][currP] = match[0][lastP] // .* pattern can match len 0 string
  23. }
  24. // Start from the first char of string
  25. for currS := 1; currS <= len(s); currS++ {
  26. charS := s[currS-1]
  27. if !zeroOrMore {
  28. // s1s2...sx ~ p1p2...py <=> s1...s(x-1) ~ p1...p(x-1) && sx ~ py
  29. match[currS][currP] = match[currS-1][lastP] &&
  30. (charP == '.' || charS == charP)
  31. } else {
  32. // ... <=> s1...sx ~ p1...p(y-1) [ie. py matches nothing] ||
  33. // (sx ~ sy && s1...s(x-1) ~ p1...py)
  34. match[currS][currP] = match[currS][lastP] ||
  35. ((charP == '.' || charS == charP) &&
  36. match[currS-1][currP])
  37. }
  38. }
  39. lastP = currP
  40. currP++
  41. }
  42. return match[len(s)][len(p)]
  43. }
  44. // func main() {
  45. // fmt.Println(isMatchRegex("", ""))
  46. // fmt.Println(isMatchRegex("ssssss", "p"))
  47. // fmt.Println(isMatchRegex("ssssss", "s*"))
  48. // fmt.Println(isMatchRegex("ssssss", "s.*s"))
  49. // fmt.Println(isMatchRegex("ss", "s.*ss"))
  50. // fmt.Println(isMatchRegex("ss", "s*"))
  51. // }