正则表达式匹配

题目描述:给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。

‘.’ 匹配任意单个字符
‘*’ 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/regular-expression-matching/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历、递归

遍历p,将s和p进行匹配。分几种情况,分别是 ‘.’ 或 ‘‘ 或者两者都不是的情况, ‘.’ 和两者都不是的相对比较简单,比较复杂点的是’*’的判断,因为’‘是匹配零个或多个元素,所以用到了递归。

  1. public class Solution {
  2. public static boolean isMatch(String s, String p) {
  3. if ((s == null || s.length() == 0) && (p == null || p.length() == 0)) {
  4. return true;
  5. }
  6. if ((p == null || p.length() == 0) && s.length() > 0) {
  7. return false;
  8. }
  9. char preChar = 0;
  10. boolean havePreChar = false;
  11. int sIndex = 0;
  12. for (int i = 0; i < p.length(); i++) {
  13. if (p.charAt(i) == '.') {
  14. if (i < p.length() - 1 && p.charAt(i + 1) == '*') {
  15. preChar = p.charAt(i);
  16. havePreChar = true;
  17. continue;
  18. } else {
  19. if (sIndex < s.length()) {
  20. preChar = s.charAt(sIndex);
  21. sIndex++;
  22. havePreChar = true;
  23. continue;
  24. } else {
  25. return false;
  26. }
  27. }
  28. }
  29. if (p.charAt(i) == '*') {
  30. if (!havePreChar) {
  31. return false;
  32. }
  33. if (sIndex == s.length()) {
  34. if (p.length() - 1 == i) {
  35. return true;
  36. } else {
  37. return isMatch("", p.substring(i + 1));
  38. }
  39. } else {
  40. if (preChar == '.') {
  41. if (i == p.length() - 1) {
  42. return true;
  43. }
  44. while (sIndex < s.length()) {
  45. boolean result = isMatch(s.substring(sIndex), p.substring(i + 1));
  46. if (result) {
  47. return true;
  48. }
  49. sIndex++;
  50. continue;
  51. }
  52. } else {
  53. while (sIndex < s.length()) {
  54. if (s.charAt(sIndex) == preChar) {
  55. boolean result = isMatch(s.substring(sIndex), p.substring(i + 1));
  56. if (result) {
  57. return true;
  58. }
  59. sIndex++;
  60. continue;
  61. } else {
  62. break;
  63. }
  64. }
  65. }
  66. havePreChar = false;
  67. }
  68. }
  69. if (p.charAt(i) != '*' && p.charAt(i) != '.') {
  70. if (i < p.length() - 1 && p.charAt(i + 1) == '*') {
  71. preChar = p.charAt(i);
  72. havePreChar = true;
  73. continue;
  74. } else {
  75. if (sIndex == s.length() || s.charAt(sIndex) != p.charAt(i)) {
  76. return false;
  77. } else {
  78. sIndex++;
  79. havePreChar = false;
  80. continue;
  81. }
  82. }
  83. }
  84. }
  85. if (sIndex < s.length()) {
  86. return false;
  87. }
  88. return true;
  89. }
  90. public static void main(String[] args) {
  91. String s = "", p = "c*c*"; // true
  92. System.out.println(isMatch(s, p));
  93. }
  94. }