正则匹配字符串
Question:
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”, “c*a*b”) → true
Subscribe to see which companies asked this question.
在题目中“.”表示可以匹配任意一个字符,“*”表示可以匹配在他之前的那个字符可以有任意多个。例如”a*b”->”aaaaaab”;
* 当p.length==0时,判断s.lenght==0?true:false;
* 当p.length==1时,判断s.charAt(0) == p.charAt(0) || (p.charAt(0) == ‘.’ && s.length == 1)?true:false;
* 当p.length>1时,我们可以使用递归来判断s与p是否匹配!
import java.util.Scanner;
public class Solution {
public static boolean isMatch(String s, String p) {
//正则表达式匹配(“.”只能匹配单个字符,“*”可以匹配之前的多个元素)
int lenP = p.length();
int lenS = s.length();
//如果p的长度为0的话, 判断s的长度是否为零
if(lenP==0){
return lenS == 0;
}
if(lenP == 1){
if(p.equals(s) || p.equals(".") && lenS == 1){
return true;
}
return false;
}
if(p.charAt(1) != '*'){
//如果字符串p.charAt(1)!='*',我们则递归的削减字符串s和p的第一个字符来判断两者是否相同
if(lenS > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
return isMatch(s.substring(1), p.substring(1));
}
return false;
}else{
//如果字符串p.charAt(1)=='*',我们则要递归的判断s[0……s.length-1]与p[2……p.length-1]
while(s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
if(isMatch(s, p.substring(2))){
return true;
}
s = s.substring(1);
}
return isMatch(s, p.substring(2));
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s1 = in.nextLine();
String s2 = in.nextLine();
System.out.println(isMatch(s1, s2));
in.close();
}
}