반응형
문제
Given an input string s
and a pattern p
, implement regular expression matching with support for '.'
and '*'
where:
'.'
Matches any single character.'*'
Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Constraints:
1 <= s.length <= 20
1 <= p.length <= 20
s
contains only lowercase English letters.p
contains only lowercase English letters,'.'
, and'*'
.- It is guaranteed for each appearance of the character
'*'
, there will be a previous valid character to match.
풀이
받은 문자열을 패턴과 비교하여 일치하면 다음 패턴을 검사하는 방식으로 진행해보았다.
'*'가 있을 경우 이전 문자와 비교해야 하므로, 우선 문자를 비교한 후 다음 패턴 문자에 '*'가 있는 경우 다음 글자를 현재 패턴 문자와 비교 + 다음 패턴을 비교하도록 했다.
재귀적으로 만들어서 지속적으로 비교하고 다음 패턴 및 문자 비교로 넘어갈 수 있도록 코드를 작성했다.
코드
class Solution {
public boolean isMatch(String s, String p) {
return isMatch(s, p, 0, 0);
}
private boolean isMatch(String s, String p, int textIdx, int patternIdx) {
if(patternIdx == p.length()) {
return textIdx == s.length();
}
boolean checkFirstChar = (textIdx < s.length() && (s.charAt(textIdx) == p.charAt(patternIdx) || p.charAt(patternIdx) == '.'));
if(patternIdx + 1 < p.length() && p.charAt(patternIdx + 1) == '*') {
return isMatch(s, p, textIdx, patternIdx + 2) || (checkFirstChar && isMatch(s, p, textIdx + 1, patternIdx));
} else {
return checkFirstChar && isMatch(s, p, textIdx + 1, patternIdx + 1);
}
}
}
결과
Runtime : 472 ms
Memory Usage : 41.66 MB
반응형
'LeetCode' 카테고리의 다른 글
12. Integer to Roman (0) | 2024.11.30 |
---|---|
11. Container With Most Water (0) | 2024.11.24 |
8. String to Integer (atoi) (0) | 2024.11.12 |
7. Reverse Integer (0) | 2024.11.10 |
6. Zigzag Conversion (1) | 2024.11.05 |