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

思想:用变量start记录*是否出现过;用ix和iy表示*可能比配的字符,即下一次需要匹配的开端
  1. public boolean isMatch(String s, String p) {
  2. int s1 = s.length();
  3. int p1 = p.length();
  4. if(s1==0) {
  5. for(int i=0;i<p1;i++) {
  6. if(p.charAt(i) != '*') {
  7. return false;
  8. }
  9. }
  10. return true;
  11. }
  12. boolean star = false;
  13. int ix = 0;
  14. int iy = 0;
  15. int i= 0;
  16. int j=0;
  17. for(i=0,j=0;i<s1;i++,j++) { //完全匹配s1
  18. char ptmp = '#'; //java中无结尾字符
  19. if(j<p1)
  20. ptmp = p.charAt(j);
  21. switch(ptmp){
  22. case '?':
  23. break;
  24. case '*':
  25. ix = i;
  26. iy = j;
  27. star = true;
  28. while(iy<p1 && p.charAt(iy) == '*') iy++;
  29. if(iy==p1) return true;
  30. i = ix - 1;
  31. j = iy - 1;
  32. break;
  33. default:
  34. if(ptmp!=s.charAt(i)) {
  35. if(!star) {
  36. return false;
  37. }
  38. ix++;
  39. i = ix -1;
  40. j = iy - 1;
  41. }
  42. }
  43. }
  44. while(j<p1 && p.charAt(j) == '*') j++;
  45. if(j==p1) {
  46. return true;
  47. } else {
  48. return false;
  49. }
  50. }

C代码:

  1. bool isMatch(const char *s, const char *p) {
  2. bool star = false;
  3. const char *str,*ptr;
  4. for(str = s,ptr=p;*str!='\0';str++,ptr++)
  5. {
  6. switch(*ptr)
  7. {
  8. case '?':
  9. break;
  10. case '*':
  11. star=true;
  12. s=str;
  13. p=ptr;
  14. while(*p=='*')
  15. p++;
  16. if(*p=='\0')
  17. return true;
  18. str=s-1;
  19. ptr=p-1;
  20. break;
  21. default:
  22. {
  23. if(*str!=*ptr)
  24. {
  25. if(!star)
  26. return false;
  27. s++;
  28. str=s-1;
  29. ptr=p-1;
  30. }
  31. }
  32. }
  33. }
  34. while(*ptr=='*')
  35. ptr++;
  36. return (*ptr=='\0');
  37. }
posted @ 2014-08-10 21:39  purejade  阅读(116)  评论(0)    收藏  举报