Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active October 20, 2019 06:20
Show Gist options
  • Save vitkarpov/63513f1ccbb0eafeacce8cb4852f20d6 to your computer and use it in GitHub Desktop.
Save vitkarpov/63513f1ccbb0eafeacce8cb4852f20d6 to your computer and use it in GitHub Desktop.
678. Valid Parenthesis String (dynamic programming)
/**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
const n = s.length;
const dp = new Array(n).fill(0).map(() => new Array(n).fill(false));
for (let i = 0; i < n; i++) {
if (s[i] == "*") {
dp[i][i] = true;
}
if ((s[i] == "(" || s[i] == "*") && (s[i + 1] == ")" || s[i + 1] == "*")) {
dp[i][i + 1] = true;
}
}
for (let len = 2; len < n; len++) {
for (let start = 0; start + len < n; start++) {
if (s[start] == "*" && dp[start + 1][start + len]) {
dp[start][start + len] = true;
} else if (s[start] == "(" || s[start] == "*") {
for (let i = start + 1; i <= start + len; i++) {
if (
(s[i] == ")" || s[i] == "*") &&
(i == start + 1 || dp[start + 1][i - 1]) &&
(i + 1 == start + len || dp[i + 1][start + len])
) {
dp[start][start + len] = true;
}
}
}
}
}
return dp[0][n - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment