`
hcx2013
  • 浏览: 83712 次
社区版块
存档分类
最新评论

Wildcard Matching

 
阅读更多

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") → 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


public class Solution {  
    public boolean isMatch(String str, String pattern) {  
    	int s = 0;
    	int p = 0;
    	int index = -1;
    	int match = 0;
    	while (s < str.length()) {
    		if (p<pattern.length() && (str.charAt(s)==pattern.charAt(p)||pattern.charAt(p)=='?')) {
    			s++;
    			p++;
    		} else if (p<pattern.length() && pattern.charAt(p)=='*') {
    			index = p;
    			match = s;
    			p++;
    		} else if (index != -1) {
    			p = index+1;
    			match++;
    			s = match;
    		} else {
    			return false;
    		}
    	}
    	while (p<pattern.length() && pattern.charAt(p)=='*') {
    		p++;
    	}
    	return p == pattern.length();
    }
}  
 
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics