gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
Write a java program that uses Dynamic programming algorithm to solve the String…
- User
Write a java program that uses Dynamic programming algorithm to solve the String Matching problem/ wildcard pattern matching
- Assistant
Here's a Java program that uses dynamic programming to solve the wildcard pattern matching problem with "?" and "*":
public class WildcardMatching { public static void main(String[] args) { String str = "abcdef"; String pattern = "a?c*f"; System.out.println(isMatch(str, pattern)); } public static boolean isMatch(String str, String pattern) { int m = str.length(); int n = pattern.length(); boolean[][] dp = new boolean[m + 1][n + 1]; // Empty pattern can match with empty string dp[0][0] = true; // Only '*' can match with the empty string for (int j = 1; j <= n; j++) { if (pattern.charAt(j - 1) == '*') { dp[0][j] = dp[0][j - 1]; } } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { // Two cases when current character is '?', or current characters are the same if (pattern.charAt(j - 1) == '?' || str.charAt(i - 1) == pattern.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } // When current character is '*', it can either act as an empty character, or as the same character else if (pattern.charAt(j - 1) == '*') { dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; } } } return dp[m][n]; } }