Untitled

 avatar
unknown
plain_text
19 days ago
2.3 kB
4
Indexable
public class WildcardMatchingForLoop {
    // Recursive function with memoization to check if s1 matches s2
    public static boolean isMatch(int i, int j, String s1, String s2, Boolean[][] memo) {
        // Base case: Both strings are fully processed
        if (i == s1.length() && j == s2.length()) {
            return true;
        }
        // Base case: Pattern is exhausted but string isn't
        if (i == s1.length()) {
            return false;
        }
        // Base case: String is exhausted but pattern isn't
        if (j == s2.length()) {
            // Check if remaining pattern is all '*'
            for (int k = i; k < s1.length(); k++) {
                if (s1.charAt(k) != '*') {
                    return false;
                }
            }
            return true;
        }
        // Return memoized result if it exists
        if (memo[i][j] != null) {
            return memo[i][j];
        }

        char p = s1.charAt(i); // Current character in pattern
        char s = s2.charAt(j); // Current character in string

        if (p == '*') {
            // '*' can match zero or more characters
            for (int k = j; k <= s2.length(); k++) {
                if (isMatch(i + 1, k, s1, s2, memo)) {
                    memo[i][j] = true;
                    return true;
                }
            }
            memo[i][j] = false; // If no match is found
        } else if (p == '?' || p == s) {
            // Match current characters or '?' matches any single character
            memo[i][j] = isMatch(i + 1, j + 1, s1, s2, memo);
        } else {
            // Characters don't match
            memo[i][j] = false;
        }
        return memo[i][j];
    }

    public static boolean isWildcardMatch(String s1, String s2) {
        int n = s1.length();
        int m = s2.length();
        // Create a memoization table
        Boolean[][] memo = new Boolean[n][m];
        return isMatch(0, 0, s1, s2, memo);
    }

    public static void main(String[] args) {
        String s1 = "*a*b";
        String s2 = "aaabb";
        boolean result = isWildcardMatch(s1, s2);
        System.out.println("Does the pattern \"" + s1 + "\" match the string \"" + s2 + "\"? " + result);
    }
}
Editor is loading...
Leave a Comment