1. 程式人生 > >【正則表示式判斷】Regular Expression Matching

【正則表示式判斷】Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
參考:http://blog.csdn.net/fightforyourdream/article/details/17717873
public class Solution {
    
    public boolean isMatch(String s, String p, int sp, int pp){
        int ls = s.length();
        int lp = p.length();
        
        if(pp >= lp) return sp>=ls;
        
        if(pp == lp-1) return (sp==ls-1) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.');
        
        if(pp+1 < lp && p.charAt(pp + 1) != '*'){//如果下一個字元不為*,則比較s和p當前的字元
            if((sp!=ls) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.'))
            return isMatch(s, p, sp+1, pp+1);
            else return false;
        }
        else{//若下一個字元為*
            while((sp<ls) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.')){
                if(isMatch(s, p, sp, pp+2)) return true;//如果把當前s中字元放入後續匹配成功,即p的下一*沒有用
                sp++;//不成功則將*執行一次
            }
            return isMatch(s, p, sp, pp+2);
        }
    }
    
    public boolean isMatch(String s, String p) {
        return isMatch(s, p, 0, 0);
    }
}