鍍金池/ 教程/ Java/ Regular Expression Matching (正則表達式匹配)
ZigZag Conversion(Z型轉(zhuǎn)換)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Generate Parentheses(生成括號)
Longest Common Prefix(最長公共前綴)
Remove Duplicates from Sorted Array(從已排序數(shù)組中移除重復(fù)元素)
Swap Nodes in Pairs(交換序列中的結(jié)點)
Valid Parentheses(有效的括號)
4 Sum(4 個數(shù)的和)
3 Sum(3 個數(shù)的和)
3 Sum Closest(最接近的 3 個數(shù)的和)
Reverse Nodes in k-Group(在K組鏈表中反轉(zhuǎn)結(jié)點)
Regular Expression Matching (正則表達式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個已排序的數(shù)組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個結(jié)點)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Palindrome Number(回文數(shù))
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數(shù)到整型數(shù))
Integer to Roman(整型數(shù)到羅馬數(shù))
Reverse Integer(翻轉(zhuǎn)整數(shù))
Merge k Sorted Lists(合并 K 個已排序鏈表)
Implement strStr()(實現(xiàn) strStr() 函數(shù))
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號碼的字母組合)

Regular Expression Matching (正則表達式匹配)

翻譯

實現(xiàn)支持“.”和“*”的正則表達式匹配。

“.” 匹配支持單個字符
“*” 匹配零個或多個前面的元素

匹配應(yīng)該覆蓋到整個輸入的字符串(而不是局部的)。

該函數(shù)的原型應(yīng)該是:

bool isMatch(const char s, const char p)

示例:

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

原文

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

C#,遞歸

public class Solution
{
    public bool IsMatch(string s, string p)
    {
        if (p.Length == 0)
            return s.Length == 0;

        if (p.Length == 1)
            return (s.Length == 1) && (p[0] == s[0] || p[0] == '.');

        if (p[1] != '*')
        {
            if (s.Length == 0)
                return false;
            else
                return (s[0] == p[0] || p[0] == '.')
                       && IsMatch(s.Substring(1), p.Substring(1));
        }
        else
        {
            while (s.Length > 0 && (p[0] == s[0] || p[0] == '.'))
            {
                if (IsMatch(s, p.Substring(2)))
                    return true;
                s = s.Substring(1);
            }
            return IsMatch(s, p.Substring(2));
        }
    }
}