leetcode-44 Wildcard Matching 通配符匹配
来源:互联网 发布:u盘维护系统 数据恢复 编辑:程序博客网 时间:2024/05/16 05:05
问题描述:
Implementwildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters(including the empty sequence).
The matching should cover theentireinput 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", "*") →true
isMatch("aa", "a*") →true
isMatch("ab", "?*") →true
isMatch("aab", "c*a*b")→ false
问题分析:
类似相关问题,如正则表达式匹配问题:《leetcode-10 Regular Expression Matching》
本题采用双指针的方法,分别对s,p进行按位匹配;
当p[j]不为‘*’时较简单,直接进行单位匹配即可;
当为‘*’时,要注意出现不匹配情况下的回溯,因此需要将‘*’的信息记录下来,需要记录的信息有‘*’对应在p中的位置,以及匹配s的最远位置;便于需要回溯时恢复原始状态继续进行匹配。
代码:
public class Solution { public boolean isMatch(String s,String p) { // i,j分别表示记录s与p的双指针,match用来记录前一个'*'匹配的长度,'*'用来记录前一个'*'的位置 int i = 0, j = 0, match =0, star = -1; while (i < s.length()) { // '?'匹配情况与s[i]==p[j]情况 if (j < p.length() &&(p.charAt(j) == '?'|| s.charAt(i) == p.charAt(j))) { i++; j++; } // p[j]='*'时,记录下来该位置star,match用来记录该'*'能够匹配的s的最远距离 else if (j < p.length()&& p.charAt(j) == '*') { // 记录下此时'*'的位置信息,以及对应的s的位置信息,这里也相当于表示'*'表示0个字节 star= j; match = i; j++; } // 出现不匹配情况,回溯至'*'继续进行匹配 else if (star != -1) { // 回溯到前面'*'处,继续进行匹配 j= star + 1; // 尝试s向前忽略一位,继续进行匹配 match++; i= match; } // 完全不匹配情况 else return false; } // 考虑残留多个'*'的特殊情况 while (j < p.length()&& p.charAt(j) == '*') j++; return j == p.length(); }}
- leetcode-44 Wildcard Matching 通配符匹配
- LeetCode: Wildcard Matching (通配符匹配)
- [leetcode] Wildcard Matching 通配符匹配
- [LeetCode]Wildcard Matching 通配符匹配(贪心)
- Wildcard Matching 通配符匹配
- Wildcard Matching 通配符匹配
- Wildcard Matching 通配符匹配
- Wildcard Matching:通配符匹配
- 通配符匹配字符串 Wildcard Matching
- [Lintcode]Wildcard Matching 通配符匹配
- LeetCode OJ 之 Wildcard Matching(通配符匹配)
- leetCode 44.Wildcard Matching (通配符匹配) 解题思路和方法
- Leetcode #44. Wildcard Matching 通配符匹配 解题报告
- 通配符匹配 & 正则表达式匹配【leetcode Wildcard Matching & Regular Expression Matching】
- leetcode Wildcard Matching ,Regular Expression Matching (正则表达式匹配和通配符匹配)
- [LeeCode]—Wildcard Matching 通配符匹配问题
- 44. Wildcard Matching(通配符匹配)
- LeetCode------44. Wildcard Matching(?*匹配)
- hadoop 数据挖掘
- 【特种兵PPT教程】簇状柱形图你用对了吗?
- C语言数据结构-树
- Android官方API Guide学习之二 设备兼容性
- Android 五大布局之(一) 线性布局和相对布局
- leetcode-44 Wildcard Matching 通配符匹配
- linux启动新进程
- 从网络获取json并解析得简单天气预报实现
- 交叉验证
- abstract interface区别
- HDU4778 Gems Fight!(记忆化搜索+博弈)
- poj 3253 Fence Repair
- 10.13 js入门
- char 和unsigned char 区别