mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-21 21:11:57 +03:00
feat: add Longest Valid Parentheses LeetCode problem (#1166)
Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
parent
1d4ccc39a9
commit
8992d267ac
@ -24,6 +24,7 @@
|
||||
| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C](./src/27.c) | Easy |
|
||||
| 28 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C](./src/28.c) | Easy |
|
||||
| 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C](./src/29.c) | Medium |
|
||||
| 32 | [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/) | [C](./src/32.c) | Hard |
|
||||
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C](./src/35.c) | Easy |
|
||||
| 38 | [Count and Say](https://leetcode.com/problems/count-and-say/) | [C](./src/38.c) | Easy |
|
||||
| 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C](./src/42.c) | Hard |
|
||||
|
60
leetcode/src/32.c
Normal file
60
leetcode/src/32.c
Normal file
@ -0,0 +1,60 @@
|
||||
#define max(x,y)(((x)>(y))?(x):(y))
|
||||
|
||||
const int notCalculated = -2;
|
||||
const int notValid = -1;
|
||||
|
||||
int getEndValidIndexFromDp(int* dp, char* s, int index, int lenS){
|
||||
if (index >= lenS){
|
||||
return notValid;
|
||||
}
|
||||
|
||||
if (dp[index] == notCalculated){
|
||||
dp[index] = getEndValidIndex(dp, s, index, lenS);
|
||||
}
|
||||
|
||||
return dp[index];
|
||||
}
|
||||
|
||||
int getEndValidIndex(int* dp, char* s, int index, int lenS){
|
||||
if (s[index] == '('){
|
||||
if (index + 1 >= lenS){
|
||||
return notValid;
|
||||
}
|
||||
|
||||
if (s[index + 1] == ')'){
|
||||
return max(index + 1, getEndValidIndexFromDp(dp, s, index + 2, lenS));
|
||||
}
|
||||
|
||||
int nextEndValidIndex = getEndValidIndexFromDp(dp, s, index + 1, lenS);
|
||||
if (nextEndValidIndex == notValid || nextEndValidIndex + 1 >= lenS || s[nextEndValidIndex + 1] != ')') {
|
||||
return notValid;
|
||||
}
|
||||
|
||||
return max(nextEndValidIndex + 1, getEndValidIndexFromDp(dp, s, nextEndValidIndex + 2, lenS));
|
||||
}
|
||||
|
||||
return notValid;
|
||||
}
|
||||
|
||||
// Dynamic Programming. UP -> down approach.
|
||||
// Runtime: O(n)
|
||||
// Space: O(n)
|
||||
int longestValidParentheses(char * s){
|
||||
int lenS = strlen(s);
|
||||
if (lenS == 0){
|
||||
return 0;
|
||||
}
|
||||
|
||||
int* dp = malloc(lenS * sizeof(int));
|
||||
for(int i = 0; i < lenS; i++){
|
||||
dp[i] = notCalculated;
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
for(int i = 0; i < lenS; i++){
|
||||
result = max(result, getEndValidIndexFromDp(dp, s, i, lenS) - i + 1);
|
||||
}
|
||||
|
||||
free(dp);
|
||||
return result;
|
||||
}
|
Loading…
Reference in New Issue
Block a user