Advertisement
Guest User

Untitled

a guest
Feb 24th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. class Solution {
  2. public boolean isMatch(String s, String p) {
  3.  
  4. if(p.isEmpty() && s.isEmpty()) {
  5. return true;
  6. }
  7.  
  8. if(p.isEmpty() && !s.isEmpty()) {
  9. return false;
  10. }
  11.  
  12. char pChar = p.charAt(0);
  13. boolean isWildcard = false;
  14.  
  15. if(p.length() > 1) {
  16. isWildcard = p.charAt(1) == '*';
  17. }
  18. if(pChar == '.') {
  19. return validateDot(isWildcard, s, p);
  20.  
  21. } else if (pChar >= 'a' && pChar <= 'z') {
  22. return validateDigit(pChar, isWildcard, s, p);
  23. } else {
  24. return false;
  25. }
  26. }
  27.  
  28. private boolean validateDigit(char c, boolean isWildcard, String s, String p) {
  29.  
  30. if(!s.isEmpty()) {
  31. if (c == s.charAt(0)) {
  32. int sumChars = sumSequentialChars(c, s);
  33. if (!isWildcard) {
  34. return isMatch(s.substring(1), p.substring(1));
  35. } else {
  36. return isMatch(s, p.substring(2)) || isMatch(s.substring(sumChars), p.substring(2)) || isMatch(s.substring(1), p);
  37. }
  38. }
  39. if (c != s.charAt(0) && isWildcard) {
  40. return isMatch(s, p.substring(2));
  41. }
  42. } else if(isWildcard) {
  43. return isMatch(s, p.substring(2));
  44. }
  45. return false;
  46. }
  47.  
  48. private boolean validateDot(boolean isWildcard, String s, String p) {
  49. if(s.isEmpty()) {
  50. if(!isWildcard) {
  51. return false;
  52. }
  53. }
  54. if(s.isEmpty()) {
  55. return isMatch(s, p.substring(2));
  56. }
  57. if(!isWildcard) {
  58. return isMatch(s.substring(1), p.substring(1));
  59. } else {
  60. int sumChars = sumSequentialChars(s.charAt(0), s);
  61. return isMatch(s, p.substring(2)) || isMatch(s.substring(sumChars), p.substring(2))
  62. || isMatch(s.substring(1), p);
  63. }
  64. }
  65.  
  66. private int sumSequentialChars(char c, String s) {
  67. int res = 0;
  68. while(res < s.length() && c == s.charAt(res)) {
  69. res++;
  70. }
  71. return res;
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement