JAVA-记笔记 三种解法
字符串通配符
http://www.nowcoder.com/questionTerminal/43072d50a6eb44d2a6c816a283b02036
搬运了三个题解中的别的 小记一下
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String in; while((in = br.readLine())!=null){ String temp = br.readLine(); //System.out.println(isMatch(temp,in)); System.out.println(getOc(in,temp)); //System.out.println(getOc(in,temp,0,0)); } } public static boolean getOc(String s1,String s2,int p1,int p2){ //递归求解 //base case if (p1 == s1.length() && p2 == s2.length()){ return true; }else if (p1 == s1.length() || p2 == s2.length()){ return false; } //遇到'*'两种情况,要不就各跳过一个比较后面,要不就s2继续往后跳先不比较 if (s1.charAt(p1) == '*'){ return getOc(s1, s2, p1, p2+1) || getOc(s1, s2, p1+1, p2+1); //遇到'?'跟两个一样操作一样,直接指针都往后移一个继续比较 }else if (s1.charAt(p1) == '?' || s1.charAt(p1) == s2.charAt(p2)){ return getOc(s1, s2, p1+1, p2+1); }else { return false; } }//method end public static boolean getOc(String in,String temp){ //字符串通配符 in = in.replaceAll("\\?", "[0-9A-Za-z]{1}"); in = in.replaceAll("\\*", "[0-9A-Za-z]{0,}"); //in = in.replaceAll("\\.", "\\\\."); return temp.matches(in); } public static boolean isMatch(String s, String p) { //动态规划 if(s.length() == 0 && p.length() == 0)return true; if(s.length()!= 0 && p.length() == 0) return false; boolean [][] dp = new boolean [s.length()+1][p.length()+1]; dp[0][0] = true; for(int j = 2; j <= p.length(); j++){ if(p.charAt(j-1) == '*' && dp[0][j-2]){ dp[0][j] = true; } } for(int i = 1; i <= s.length(); i++){ for(int j = 1; j <= p.length(); j++){ char a = s.charAt(i-1), b = p.charAt(j-1); if(a == b || b == '?'){ dp[i][j] = dp[i-1][j-1]; } else if(b == '*'){ if(j>=2){ dp[i][j] = dp[i-1][j] || dp[i][j-2]; } } else dp[i][j] = false; } } return dp[s.length()][p.length()]; } }