【LeetCode】45. Wildcard Matching

题目描述(Hard)

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

题目链接

https://leetcode.com/problems/wildcard-matching/description/

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

算法分析

回溯法,每当遇到'*'时,就保留当前的'*'的坐标(下一位作为回溯位)和s的坐标,然后s从前往后扫描,如果不成功,则回溯,并且回溯位后移++s,重新扫描,时间复杂度O(m*n)

提交代码:

class Solution {
public:
	bool isMatch(string s, string p) {
		return isMatchCore(s.c_str(), p.c_str());
	}

	bool isMatchCore(const char *s, const char *p)
	{
		bool star = false;
		const char *str, *ptr;
		for (str = s, ptr = p; *str != '\0'; ++str, ++ptr)
		{
			if (*ptr == '?') continue;
			else if (*ptr == '*')
			{
				star = true;				
				p = ptr, s = str;
				while (*p == '*') ++p;
				if (*p == '\0') return true;
				ptr = p - 1;
				str = s - 1;
			}
			else
			{
				if (*ptr != *str)
				{
					if (!star) return false;
					++s;
					ptr = p - 1;
					str = s - 1;
				}
			}
		}

		while (*ptr == '*') ++ptr;
		return (*ptr == '\0');
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string str, string p, bool expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	bool result = s.isMatch(str, p);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("aa"), string("a"), false);
	Test("Test2", string("aa"), string("*"), true);
	Test("Test3", string("cb"), string("?a"), false);
	Test("Test4", string("adceb"), string("*a*b"), true);
	Test("Test5", string("acdcb"), string("a*c?b"), false);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82426273