2222 */
2323
2424/**
25+ *
26+ * 解题思路
27+ *
28+ * 动态规划
29+ * 注意体感要求, isMatch 为全匹配
30+ * 例子中的 isMatch("aab", "c*a*b") -> true
31+ * 是因为匹配 0个c, 2个a, 一个b
32+ *
2533 * @param {string } s
2634 * @param {string } p
2735 * @return {boolean }
@@ -40,17 +48,30 @@ var isMatch = function (s, p) {
4048 for ( var i = 0 ; i <= m ; i ++ ) {
4149 for ( var j = 1 ; j <= n ; j ++ ) {
4250 if ( p [ j - 1 ] === '*' ) {
43- dp [ i ] [ j ] = dp [ i ] [ j - 2 ] || ( i > 0 && ( s [ i - 1 ] === p [ j - 2 ] || p [ j - 2 ] === '.' ) && dp [ i - 1 ] [ j ] ) ;
51+ // isMatch('a', 'a.*')
52+ // 如果j-1是*, 那么j-2可以出现0次;
53+ // 所以可以直接看 dp[i][j-2]
54+ dp [ i ] [ j ] = dp [ i ] [ j - 2 ] ||
55+ // isMatch('aa', 'aa*')
56+ ( i > 0 && ( s [ i - 1 ] === p [ j - 2 ] || p [ j - 2 ] === '.' ) && dp [ i - 1 ] [ j ] ) ;
4457 } else {
4558 dp [ i ] [ j ] = i > 0 && dp [ i - 1 ] [ j - 1 ] &&
4659 ( s [ i - 1 ] === p [ j - 1 ] || p [ j - 1 ] === '.' ) ;
4760 }
4861 }
4962 }
5063
51- // console.log(dp);
64+ console . log ( dp . map ( a => a . map ( a => a ? 1 : 0 ) ) ) ;
5265 return dp [ m ] [ n ] ;
5366} ;
5467
55- console . log ( isMatch ( "aab" , "c*a*b" ) ) ;
56- console . log ( isMatch ( "aasdfasdfasdfasdfas" , "aasdf.*asdf.*asdf.*asdf.*s" ) ) ;
68+ // console.log(isMatch("aa", "a"), '→', false)
69+ // console.log(isMatch("aa", "aa"), '→', true)
70+ // console.log(isMatch("aaa", "aa"), '→', false)
71+ // console.log(isMatch("aa", "a*"), '→', true)
72+ // console.log(isMatch("aa", ".*"), '→', true)
73+ // console.log(isMatch("ab", ".*"), '→', true)
74+ // console.log(isMatch("aab", "c*a*b"), '→', true)
75+
76+ console . log ( isMatch ( "a" , "a.*" ) ) ;
77+ // console.log(isMatch("aasdfasdfasdfasdfas", "aasdf.*asdf.*asdf.*asdf.*s"));
0 commit comments