Untitled
unknown
plain_text
17 days ago
1.2 kB
3
Indexable
class Solution { public boolean isMatch(String s, String p) { return matchHelper(s, p, s.length() - 1, p.length() - 1); } private boolean matchHelper(String s, String p, int i, int j) { // Base case: if the pattern is exhausted, check if the string is also exhausted if (j < 0) { return i < 0; } // Check if the current characters match or if the pattern has a '.' boolean currentMatch = (i >= 0 && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.')); // Handle the '*' case if (j > 0 && p.charAt(j) == '*') { // Match zero or more of the preceding element (p[j-1]) return matchHelper(s, p, i, j - 2) // Skip '*' and its preceding element || (i >= 0 && (s.charAt(i) == p.charAt(j - 1) || p.charAt(j - 1) == '.') // Match preceding element && matchHelper(s, p, i - 1, j)); // Use '*' to match current character } // If no '*', move to the previous characters in both the string and the pattern return currentMatch && matchHelper(s, p, i - 1, j - 1); } }
Editor is loading...
Leave a Comment