Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. public boolean isMatchTLE(String s, String p) {
  2. if (s == null || p == null) {
  3. return false;
  4. }
  5.  
  6. return isMatchHelper(s, 0, p, 0);
  7. }
  8.  
  9. // b*b*ab**ba*b**b***bba , this should trim some of the recursion time
  10. public String removeDuplicateStars(String p) {
  11. String newP = "";
  12.  
  13. for (int i = 0; i < p.length(); i++) {
  14. if (p.charAt(i) != '*') {
  15. newP += p.charAt(i);
  16. } else {
  17. if (newP.length() == 0 || newP.charAt(newP.length() - 1) != '*') {
  18. newP += "*";
  19. }
  20. }
  21. }
  22.  
  23. return newP;
  24. }
  25.  
  26. // Even after all those optimizations, this would still TLE, n*2^m
  27. private boolean isMatchHelper(String s, int i, String p, int j) {
  28. if (j == p.length()) {
  29. return i == s.length();
  30. }
  31. p = this.removeDuplicateStars(p);
  32.  
  33. if (p.charAt(j) == '*') {
  34. // s = "abcdef"
  35. // p = "*bc*def"
  36. if (isMatchHelper(s, i, p, j + 1)) {
  37. return true;
  38. }
  39. if (i == s.length() - 1 && j == p.length() - 1) {
  40. return true;
  41. }
  42. for (int k = i + 1; k < s.length(); k++) {
  43. return isMatchHelper(s, k, p, j);
  44. }
  45. } else {
  46. if (isCharMatch(s, i, p, j)) {
  47. return isMatchHelper(s, i + 1, p, j + 1);
  48. }
  49. return false;
  50. }
  51. return false;
  52. }
  53.  
  54. // compare if char is the same or it is a '?'
  55. private boolean isCharMatch(String s, int i, String p, int j) {
  56. if (i >= s.length() || j >= p.length()) {
  57. return false;
  58. }
  59. return s.charAt(i) == p.charAt(j) || p.charAt(j) == '?';
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement