2024. 3. 13. 20:53ㆍTech: Algorithm
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.
Solution
regular expression을 함수로 만든다 보면 되는데, string s를 순회하면서 string p와 비교하는데
1. p_{i} 가 'a' ~ 'z'인데 s와 다르면 False return
2. p_{i} 가 '.'
2-1. p_{i+1} *이면 다음 p문자와 비교 ( a.* 일때는 return true이지만 a.*a 이면 끝문자가 a여야지만 return true)
2-2. p_{i+1}가 일반 문자면 s 문자 하나만 pass
3. p_{i}가 '*'
3-1. p_{i-1}가 일반 문자면 p_{i+1}문자가 나올때까지 s 를 pass
하지만 이렇게 했을 때
s= 'aab' / p='c*a*b' 의 경우 true가 나와야하는데 false가 나와서 fail했는데... 이게 *는 0일수도 있다는 경우가 안들어갔다..!
3-1. 안나와도 ok
를 추가해야했다. 이런 식으로 풀다가는 끝이 안날 것 같아서 답을 보니.. DP Dynamic Programming... 오랜만에 보는군
어떻게 이런 생각을 할까..
We define dp[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. The state equations will be:
- dp[i][j] = dp[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
- dp[i][j] = dp[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 time;
- dp[i][j] = dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 time.
class Solution {
public:
bool isMatch(string s, string p) {
int n = s.length(), m = p.length();
bool dp[n+1][m+1];
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for(int i=0;i<=n;i++){
for(int j=1;j<=m;j++){
if(p[j-1]=='*'){
dp[i][j] = dp[i][j-2] || (i>0 && (s[i-1]==p[j-2] || p[j-2]=='.') && dp[i-1][j]);
}
else{
dp[i][j]=i>0 && dp[i-1][j-1] && (s[i-1]==p[j-1] || p[j-1]=='.');
}
}
}
return dp[n][m];
}
};
'Tech: Algorithm' 카테고리의 다른 글
[Leetcode] 11. Container With Most Water (0) | 2024.03.18 |
---|---|
[Leetcode] 9. Palindrome Number (0) | 2024.03.12 |
[Leetcode] 8. String to Integer (atoi) (0) | 2024.03.12 |
[Leetcode] 7. Reverse Integer (0) | 2024.03.11 |
[Leetcode] 6. Zigzag Conversion (0) | 2024.03.08 |