From 8992d267ac4f067da6b4ecfd17742b91efc0d35a Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Sat, 17 Dec 2022 01:37:54 +0400 Subject: [PATCH] feat: add Longest Valid Parentheses LeetCode problem (#1166) Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/32.c | 60 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 leetcode/src/32.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 3b7fd16b..78bddea3 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -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 | diff --git a/leetcode/src/32.c b/leetcode/src/32.c new file mode 100644 index 00000000..ce05249a --- /dev/null +++ b/leetcode/src/32.c @@ -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; +}