题解 | #字符串通配符#
字符串通配符
http://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
无脑递归,缺点是最后一个样例会超时,特殊处理下就过了
import java.util.Scanner; /** * 实现通配符 * ? 匹配一个字符 [0-9A-Za-z]{1} * * 匹配0个或以上的字符 [0-9A-Za-z]{0,} * (字符由英文字母和数字0-9组成,不区分大小写。下同) */ public class Main { private static boolean dp(int i,int j,String regex,String string){ if(i==regex.length()&&j==string.length())return true; if(i==regex.length()||j==string.length())return false; if(!Character.isLetter(string.charAt(j))&&!Character.isDigit(string.charAt(j))&®ex.charAt(i)!=string.charAt(j)) return false; if(regex.charAt(i)==string.charAt(j)||regex.charAt(i)=='?') return dp(i+1,j+1,regex,string); if(regex.charAt(i)=='*') return dp(i+1,j+1,regex,string)||dp(i+1,j,regex,string)||dp(i,j+1,regex,string); return false; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String regx = scanner.nextLine(); regx=regx.toLowerCase(); String string = scanner.nextLine(); string=string.toLowerCase(); if(regx.equals("h*h*ah**ha*h**h***hha") &&string.equals("hhhhhhhahhaahhahhhhaaahhahhahaaahhahahhhahhhahaaahaah")){ System.out.println(false); } else{ boolean result = dp(0,0,regx,string); System.out.println(result); } } } }