leetcode-剑指19-OK

// language C with STL(C++)
// 剑指19
// https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/
// 偷师题解

class Solution {
public:
	int getnum(string what, char a){
		int num = 0;
		int len = what.length();
		for(int i =0; i<len; i++){
			if(what[i] == a)
				num++;
		}
        return num;
	}


    bool isMatch(string s, string p) {
    	int len_s = s.length();
    	int len_p = p.length();
    	int num_star = getnum(p,'*');
    	int num_dot  = getnum(p,'.');
    	if(len_s == 0){
    		if(len_p == 2 *num_star){
    			return true;
    		}else{
    			return false;
    		}
    	}
    	bool res[len_s+1][len_p+1];

    	for(int i = 0; i <= len_s; i++){
    		for(int j = 0; j <= len_p; j++){
    				res[i][j] = false;
    		}
    	}

    	for(int i = 0; i <= len_s; i++){
    		for(int j = 0; j <= len_p; j++){
    			if(j == 0 )
    				res[i][j] = (i==0);
    			else{
    				if(p[j-1] != '*'){
    					if(i>0 && (s[i-1]== p[j-1] || p[j-1] == '.')){
    						res[i][j] = res[i-1][j-1];
    					}
    				}else{
    					if(j>=2){
    						res[i][j] |= res[i][j-2];
    					}
    					if(i>0 && j>=2 && (s[i-1]== p[j-2] || p[j-2] == '.')){
    						res[i][j] |= res[i-1][j];
    					}
    				}
    			}
    		}
    	}
    	return res[len_s][len_p];
    }
};
posted @ 2021-02-09 21:35  RougeBW  阅读(24)  评论(0编辑  收藏  举报