Solución
solution.tsTypeScript
export function regexMatch(text: string, pattern: string): boolean {
const m = text.length;
const n = pattern.length;
// Inicializamos la matriz dp de (m + 1) x (n + 1) con valores false
const dp: boolean[][] = Array(m + 1).fill(false).map(() => Array(n + 1).fill(false));
// Caso base: un texto vacío coincide con un patrón vacío
dp[0][0] = true;
// Inicialización para patrones que pueden coincidir con un texto vacío (ej. "a*", ".*")
for (let j = 1; j <= n; j++) {
if (pattern[j - 1] === '*') {
dp[0][j] = dp[0][j - 2];
}
}
// Llenado de la matriz dp
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
// Si hay coincidencia exacta o es un punto '.'
if (pattern[j - 1] === '.' || pattern[j - 1] === text[i - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
// Si encontramos un asterisco '*'
else if (pattern[j - 1] === '*') {
// Opción 1: Ignorar el asterisco y el carácter anterior (0 repeticiones)
dp[i][j] = dp[i][j - 2];
// Opción 2: Usar el asterisco para 1 o más repeticiones si el carácter anterior coincide
if (pattern[j - 2] === '.' || pattern[j - 2] === text[i - 1]) {
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
}
}
}
return dp[m][n];
}0respuestas