返回介绍

solution / 0600-0699 / 0678.Valid Parenthesis String / README_EN

发布于 2024-06-17 01:03:35 字数 7607 浏览 0 评论 0 收藏 0

678. Valid Parenthesis String

中文文档

Description

Given a string s containing only three types of characters: '(', ')' and '*', return true _if_ s _is valid_.

The following rules define a valid string:

  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".

 

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "(*)"
Output: true

Example 3:

Input: s = "(*))"
Output: true

 

Constraints:

  • 1 <= s.length <= 100
  • s[i] is '(', ')' or '*'.

Solutions

Solution 1: Dynamic Programming

Let dp[i][j] be true if and only if the interval s[i], s[i+1], ..., s[j] can be made valid. Then dp[i][j] is true only if:

  • s[i] is '*', and the interval s[i+1], s[i+2], ..., s[j] can be made valid;

  • or, s[i] can be made to be '(', and there is some k in [i+1, j] such that s[k] can be made to be ')', plus the two intervals cut by s[k] (s[i+1: k] and s[k+1: j+1]) can be made valid;

  • Time Complexity: $O(n^3)$, where $n$ is the length of the string. There are $O(n^2)$ states corresponding to entries of dp, and we do an average of $O(n)$ work on each state.

  • Space Complexity: $O(n^2)$.

class Solution:
  def checkValidString(self, s: str) -> bool:
    n = len(s)
    dp = [[False] * n for _ in range(n)]
    for i, c in enumerate(s):
      dp[i][i] = c == '*'
    for i in range(n - 2, -1, -1):
      for j in range(i + 1, n):
        dp[i][j] = (
          s[i] in '(*' and s[j] in '*)' and (i + 1 == j or dp[i + 1][j - 1])
        )
        dp[i][j] = dp[i][j] or any(
          dp[i][k] and dp[k + 1][j] for k in range(i, j)
        )
    return dp[0][-1]
class Solution {
  public boolean checkValidString(String s) {
    int n = s.length();
    boolean[][] dp = new boolean[n][n];
    for (int i = 0; i < n; ++i) {
      dp[i][i] = s.charAt(i) == '*';
    }
    for (int i = n - 2; i >= 0; --i) {
      for (int j = i + 1; j < n; ++j) {
        char a = s.charAt(i), b = s.charAt(j);
        dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')')
          && (i + 1 == j || dp[i + 1][j - 1]);
        for (int k = i; k < j && !dp[i][j]; ++k) {
          dp[i][j] = dp[i][k] && dp[k + 1][j];
        }
      }
    }
    return dp[0][n - 1];
  }
}
class Solution {
public:
  bool checkValidString(string s) {
    int n = s.size();
    vector<vector<bool>> dp(n, vector<bool>(n));
    for (int i = 0; i < n; ++i) {
      dp[i][i] = s[i] == '*';
    }
    for (int i = n - 2; i >= 0; --i) {
      for (int j = i + 1; j < n; ++j) {
        char a = s[i], b = s[j];
        dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]);
        for (int k = i; k < j && !dp[i][j]; ++k) {
          dp[i][j] = dp[i][k] && dp[k + 1][j];
        }
      }
    }
    return dp[0][n - 1];
  }
};
func checkValidString(s string) bool {
  n := len(s)
  dp := make([][]bool, n)
  for i := range dp {
    dp[i] = make([]bool, n)
    dp[i][i] = s[i] == '*'
  }
  for i := n - 2; i >= 0; i-- {
    for j := i + 1; j < n; j++ {
      a, b := s[i], s[j]
      dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1])
      for k := i; k < j && !dp[i][j]; k++ {
        dp[i][j] = dp[i][k] && dp[k+1][j]
      }
    }
  }
  return dp[0][n-1]
}

Solution 2: Greedy

Scan twice, first from left to right to make sure that each of the closing brackets is matched successfully, and second from right to left to make sure that each of the opening brackets is matched successfully.

  • Time Complexity: $O(n)$, where $n$ is the length of the string.
  • Space Complexity: $O(1)$.
class Solution:
  def checkValidString(self, s: str) -> bool:
    x = 0
    for c in s:
      if c in '(*':
        x += 1
      elif x:
        x -= 1
      else:
        return False
    x = 0
    for c in s[::-1]:
      if c in '*)':
        x += 1
      elif x:
        x -= 1
      else:
        return False
    return True
class Solution {
  public boolean checkValidString(String s) {
    int x = 0;
    int n = s.length();
    for (int i = 0; i < n; ++i) {
      if (s.charAt(i) != ')') {
        ++x;
      } else if (x > 0) {
        --x;
      } else {
        return false;
      }
    }
    x = 0;
    for (int i = n - 1; i >= 0; --i) {
      if (s.charAt(i) != '(') {
        ++x;
      } else if (x > 0) {
        --x;
      } else {
        return false;
      }
    }
    return true;
  }
}
class Solution {
public:
  bool checkValidString(string s) {
    int x = 0, n = s.size();
    for (int i = 0; i < n; ++i) {
      if (s[i] != ')') {
        ++x;
      } else if (x) {
        --x;
      } else {
        return false;
      }
    }
    x = 0;
    for (int i = n - 1; i >= 0; --i) {
      if (s[i] != '(') {
        ++x;
      } else if (x) {
        --x;
      } else {
        return false;
      }
    }
    return true;
  }
};
func checkValidString(s string) bool {
  x := 0
  for _, c := range s {
    if c != ')' {
      x++
    } else if x > 0 {
      x--
    } else {
      return false
    }
  }
  x = 0
  for i := len(s) - 1; i >= 0; i-- {
    if s[i] != '(' {
      x++
    } else if x > 0 {
      x--
    } else {
      return false
    }
  }
  return true
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文