LeetCode 44. Wildcard Matching
2017-06-03 18:18
483 查看
题意
两个字符串S,P,判断两个字符串是否匹配,其中P中可能含有∗和?∗表示可以匹配0个或者多个任意字符
?表示可以匹配任意的一个字符
思路
解法一:直接DFS,定义两个指针i,j,分别指向S,P,然后依次遍历,其中会出现下面几种情况:
s[i]==p[j]或者p[j]==?
当前字符匹配,i++,j++
p[j]==∗
需要向下搜索要匹配几个字符,如果后面不匹配就回溯到上一个∗
s[i]!=p[j]
表示不匹配
但是如果这样遍历的话,对于∗多的字符串,每次失败都要向上回溯,这样效率会很差,有可能会超时.
解法二:
贪心,如果当前字符为∗,记录此时S和P的当前匹配位置,当后面不匹配的时候,只需要返回一次∗即可,如果是其他情况,和搜索一样,最后检查P是否全部为∗.
代码
class Solution { public: bool isMatch(string s, string p) { size_t lenS = s.length(); size_t lenP = p.length(); int i = 0, j = 0; int locS = -1, locP = -1; while(i < lenS){ if(s[i] == p[j] || p[j] == '?'){ i++; j++; } else if(p[j] == '*'){ locS = i; locP = ++j; } else if(locP >= 0){ j = locP; i = ++locS; } else{ return false; } } while(j < lenP && p[j] == '*') j++; return j == lenP; } };
相关文章推荐
- leetcode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- [leetcode[ 【字符串】 44. Wildcard Matching
- Leetcode习题解答:44. Wildcard Matching
- [leetcode 44] Wildcard Matching
- leetcode 44. Wildcard Matching
- [leetcode] 44 Wildcard Matching
- LeetCode 44:Wildcard Matching
- leetcode 44. Wildcard Matching
- LeetCode - 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- [LeetCode]--44. Wildcard Matching
- leetcode 44. Wildcard Matching
- LeetCode44_Wildcard Matching
- LeetCode 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- leetcode(44) - Wildcard Matching
- leetcode-44. Wildcard Matching
- Leetcode||44. Wildcard Matching
- leetcode-44. Wildcard Matching