1. 程式人生 > >請實現一個函式用來匹配包括'.'和'*'的正則表示式。模式中的字元'.'表示任意一個字元,而'*'表示它前面的字元可以出現任意次(包含0次)。 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字

請實現一個函式用來匹配包括'.'和'*'的正則表示式。模式中的字元'.'表示任意一個字元,而'*'表示它前面的字元可以出現任意次(包含0次)。 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字

public class Solution {
    public boolean match(char[] str, char[] pattern)
    {
         if(str==null||pattern==null)
        {
            return false;
        }
        int strIndex=0;
        int patternIndex=0;
        return matchCore(str,strIndex,pattern,patternIndex);


    }

    private boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
        if (strIndex==str.length&&patternIndex==pattern.length)
        {
            return  true;
        }
        if (strIndex!=str.length&&patternIndex==pattern.length)
        {
            return  false;
        }

        if (patternIndex+1<pattern.length&&pattern[patternIndex+1]=='*')
        {
            if((strIndex!=str.length&&pattern[patternIndex]==str[strIndex])||(pattern[patternIndex]=='.'&&strIndex!=str.length))
            {
                return matchCore(str,strIndex,pattern,patternIndex+2)||matchCore(str,strIndex+1,pattern,patternIndex);
            }
            else
            {
                return  matchCore(str,strIndex,pattern,patternIndex+2);
            }
        }
        if ((strIndex!=str.length&&str[strIndex]==pattern[patternIndex])||(pattern[patternIndex]=='.'&&strIndex!=str.length))
        {
            return matchCore(str,strIndex+1,pattern,patternIndex+1);
        }

        return false;
        
    }
}