先来题目:java
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
Hmm 关于这道题 刚开始看到题的时候对我来讲 首先大致的思路很容易就出来了。 而后就是大概的框架也有了。框架
主要就是状况要分清楚。关于‘.'和‘*’的用法 以及几种特殊状况。 另外刚开始,我彻底没有察觉能够直接用imatch而后我就一直在想怎么match啊怎么match啊哈哈spa
答案仅供参考啊0.0主要仍是逻辑问题 要分清楚case最重要prototype
public class Solution { public boolean isMatch(String s, String p) { //easy to think about if(p.length()==0){ return s.length()==0; } //special case if(p.length()==1){ if(s.length()<1){ return false; } else if((s.charAt(0)!=p.charAt(0))&&(p.charAt(0)!='.')){ return false; } else{ return isMatch(s.substring(1),p.substring(1)); } } //easy to write, hard to think if(p.charAt(1)!='*'){ if(s.length()<1){ return false; } else if((p.charAt(0)!=s.charAt(0))&&(p.charAt(0)!='.')){ return false; }else{ return isMatch(s.substring(1),p.substring(1)); } } //most difficult one else{ if(isMatch(s,p.substring(2))){ return true; } int i=0; while(i<s.length()&&(s.charAt(i)==p.charAt(0)||p.charAt(0)=='.')){ if(isMatch(s.substring(i+1),p.substring(2))){ return true; } i++; } return false; } } }