입력 문자열 str과 패턴 p가 주어지면 에 대한 지원과 함께 정규식 일치를 구현해야 합니다. 및 *.
이 기호의 기능은 다음과 같아야 합니다. -
-
. --> 모든 단일 문자와 일치합니다.
-
* --> 0개 이상의 선행 요소와 일치합니다.
일치는 전체 입력 문자열을 포함해야 합니다(일부 아님).
참고
-
str은 비어 있을 수 있으며 소문자 a-z만 포함할 수 있습니다.
-
p는 비어 있을 수 있으며 소문자-z 및 다음과 같은 문자만 포함합니다. 또는 *.
예:
입력이 -
인 경우const str = 'aa'; const p = 'a';
그러면 전체 문자열 aa와 일치하지 않기 때문에 출력은 거짓이어야 합니다.
예시
다음은 코드입니다 -
const regexMatching = (str, p) => {
const ZERO_OR_MORE_CHARS = '*';
const ANY_CHAR = '.';
const match = Array(str.length + 1).fill(null).map(() => {
return Array(p.length + 1).fill(null);
});
match[0][0] = true;
for (let col = 1; col <= p.length; col += 1) {
const patternIndex = col - 1;
if (p[patternIndex] === ZERO_OR_MORE_CHARS) {
match[0][col] = match[0][col - 2];
} else {
match[0][col] = false;
}
}
for (let row = 1; row <= str.length; row += 1) {
match[row][0] = false;
}
for (let row = 1; row <= str.length; row += 1) {
for (let col = 1; col <= p.length; col += 1) {
const stringIndex = row - 1;
const patternIndex = col - 1;
if (p[patternIndex] === ZERO_OR_MORE_CHARS) {
if (match[row][col - 2] === true) {
match[row][col] = true;
} else if (
(
p[patternIndex - 1] === str[stringIndex]
|| p[patternIndex - 1] === ANY_CHAR
)
&& match[row - 1][col] === true
) {
match[row][col] = true;
} else {
match[row][col] = false;
}
} else if (
p[patternIndex] === str[stringIndex]
|| p[patternIndex] === ANY_CHAR
) {
match[row][col] = match[row - 1][col - 1];
} else {
match[row][col] = false;
}
}
}
return match[str.length][p.length];
};
console.log(regexMatching('aab', 'c*a*b')); 출력
다음은 콘솔의 출력입니다 -
true