根据题设 引入两个索引,代表子部分匹配
    跟判断两个二叉树是否是镜像
    还有一个问题是啥来着。有想通指出。

    image.png
    我的代码:暴力递归方法,
    还可以改成动态规划方法;

    1. public static void main(String[] args) {
    2. String a = "aabbc";
    3. String p = "aabb.d*e*";
    4. String aa = "ab";
    5. String pp = ".*";
    6. String aaa = "aaba";
    7. String ppp = "ab*a*c*a";
    8. System.out.println(isMatch(aaa, ppp));
    9. }
    10. public static boolean isMatch(String s, String p) {
    11. int[] freq = new int [s.length()];
    12. char pre = '0';
    13. for(int i = s.length()-1; i>=0; i--){
    14. freq[i] = 1;
    15. if(s.charAt(i)== pre){
    16. freq[i] ++;
    17. }
    18. pre = s.charAt(i);
    19. }
    20. return process(s.toCharArray(), 0, p.toCharArray(), 0 , freq);
    21. }
    22. public static boolean process(char[] s, int index1, char[] p, int index2, int[] freq){
    23. /**当pattern没有了,s还有没匹配的时候,*/
    24. if(index2 < p.length && p[index2] == '*') return false;
    25. if(index1 == s.length && index2== p.length) return true;
    26. if(index2 == p.length && index1 < s.length){
    27. return false;
    28. }
    29. if(index1 == s.length && index2 < p.length){
    30. while(index2 +1 < p.length &&p[index2 +1] == '*'){
    31. index2+=2;
    32. }
    33. if(index2==p.length) return true;
    34. else return false;
    35. }
    36. boolean res = false;
    37. if( index2 + 1 < p.length && p[index2+1]!= '*'){
    38. if(p[index2] !='.' && s[index1] != p[index2]){
    39. return false;
    40. }
    41. res = process(s, index1+1, p,index2+1, freq);
    42. }
    43. else if( index2 +1 < p.length && p[index2 +1] == '*'){
    44. /** 星号可以不匹配任何字符,也可以任意数量,只要字符相同*/
    45. if(p[index2]!='.' && p[index2] !=s[index1]){
    46. res = process(s, index1, p, index2+2, freq);
    47. return res;
    48. }
    49. else if(p[index2]!='.' && p[index2] ==s[index1]) {
    50. /** 潜台词: index1 和 index2 不命中**/
    51. for(int f = 0; f<=freq[index1];f++ ){
    52. res = res || process(s, index1 +f, p, index2+2, freq);
    53. }
    54. return res;
    55. }
    56. else if(p[index2]=='.'){
    57. for(int l = index1; l<= s.length; l ++){
    58. res = res|| process(s, l, p ,index2 +2, freq);
    59. }
    60. return res;
    61. }
    62. }
    63. else if(p[index2] == s[index1] || p[index2] == '.'){
    64. res = process(s, index1+1, p, index2 +1, freq);
    65. }
    66. return res;
    67. }