首页 > 代码库 > Wildcard Matching leetcode java
Wildcard Matching leetcode java
题目:
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)Some examples:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
题解:
本文代码引用自:http://blog.csdn.net/perfect8886/article/details/22689147
1 public boolean isMatch(String s, String p) {
2 int i = 0;
3 int j = 0;
4 int star = -1;
5 int mark = -1;
6 while (i < s.length()) {
7 if (j < p.length()
8 && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i))) {
9 ++i;
10 ++j;
11 } else if (j < p.length() && p.charAt(j) == ‘*‘) {
12 star = j++;
13 mark = i;
14 } else if (star != -1) {
15 j = star + 1;
16 i = ++mark;
17 } else {
18 return false;
19 }
20 }
21 while (j < p.length() && p.charAt(j) == ‘*‘) {
22 ++j;
23 }
24 return j == p.length();
25 }
2 int i = 0;
3 int j = 0;
4 int star = -1;
5 int mark = -1;
6 while (i < s.length()) {
7 if (j < p.length()
8 && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i))) {
9 ++i;
10 ++j;
11 } else if (j < p.length() && p.charAt(j) == ‘*‘) {
12 star = j++;
13 mark = i;
14 } else if (star != -1) {
15 j = star + 1;
16 i = ++mark;
17 } else {
18 return false;
19 }
20 }
21 while (j < p.length() && p.charAt(j) == ‘*‘) {
22 ++j;
23 }
24 return j == p.length();
25 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。