Implement regular expression matching with support for ‘.’ and ‘‘. ‘.’ 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”, “ca*b”) → true
Recursive solution
So hard to think of all the cases….
Base case: p was cut to zero Special Case: p=1, when to return false? (now p!=’‘, this case will be process next Case 1: p.charAt(1) is not ‘‘, Case 2: p.charAt(1) is ‘*’,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
publicbooleanisMatch(String s, String p){
//base case
if(p.length()==0) return s.length()==0;
//p=1 special case
if(p.length()==1 || p.charAt(1)!='*'){
//false case: s len=0;
/*if the first char of s and the first char of p is not the same,
//start from isMatch(s itself, p.substring(2)) stands for 0 preceding element
//when the '*' stands for 1 or more preceding element,try every possible number
if(isMatch(s.substring(i+1), p.substring(2)))
return true;
i++;}
}
return false;
}
Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a character b) Delete a character c) Replace a character