LeetCode 10:《Regular Expression Matching》

參考文章:http://articles.leetcode.com/2011/09/regular-expression-matching.html

LeetCode 10:《Regular Expression Matching》

參考C語言代碼實現,Java代碼實現方式如下:

    public boolean isMatch(String s, String p)
    {
        // 參考C語言的實現方式
        // 首先末尾追加#作爲結束標誌
        if (!s.contains("#"))
        {
            s += "#";
        }
        if (!p.contains("#"))
        {
            p += "#";
        }

        if (p.equals("#"))
        {
            return s.equals("#");
        }

        // 下一個字符不是‘*’:匹配當前字符
        if (p.charAt(1) != '*')
        {
            String subS = s.substring(1);
            String subP = p.substring(1);
            boolean b1 = (p.charAt(0) == s.charAt(0));
            boolean b2 = ((p.charAt(0) == '.') && !s.equals("#"));
            boolean b3 = isMatch(subS, subP);
            return (b1 || b2) && b3;
        }
        // 下一個字符是‘*’
        while((p.charAt(0) == s.charAt(0)) || ((p.charAt(0) == '.') && !s.equals("#")))
        {
            if (isMatch(s, p.substring(2)))
            {
                return true;
            }
            s = s.substring(1);
        }
        return isMatch(s, p.substring(2));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章