TypechoJoeTheme

IT技术分享

统计

[LeetCode 44] Wildcard Matching [C#]

2017-06-25
/
0 评论
/
665 阅读
/
正在检测是否收录...
06/25

1. Runtime Distribution

2. Submission Details

3. Description

Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char s, const char p)

4. Example

isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "cab") → false

5. Code

using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Csharp.DP
{
    [TestClass]
    public class LeetCode0044
    {
        public bool IsMatch(string s, string p)
        {
            bool[,] dp = new bool[s.Length + 1, p.Length + 1];

            int[] pos = new int[p.Length + 1];

            pos[0] = p.Length > 0 && p[0] == '*' ? 1 : 0;

            dp[0, 0] = true;

            for (var j = 0; j < p.Length && p[j] == '*'; j++)
            {
                dp[0, j + 1] = true;
            }

            for (var i = 1; i <= s.Length; i++)
            {
                for (var j = 1; j <= p.Length; j++)
                {
                    if (p[j - 1] == '*' && pos[j - 1] > 0)
                    {
                            dp[i, j] = true;
                            pos[j] = i;
                    }
                    else
                    {
                        dp[i, j] = (s[i - 1] == p[j - 1] || p[j - 1] == '?') && dp[i - 1, j - 1];
                        pos[j] = dp[i, j] ? i : pos[j];
                    }
                }
            }
            return dp[s.Length, p.Length];
        }

        [TestMethod]
        public void Test()
        {
            Trace.WriteLine(IsMatch("zacabz", "*a?b*"));
        }
    }
}
DP
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/427/(转载时请注明本文出处及文章链接)