返回介绍

solution / 1700-1799 / 1745.Palindrome Partitioning IV / README_EN

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

1745. Palindrome Partitioning IV

中文文档

Description

Given a string s, return true _if it is possible to split the string_ s _into three non-empty palindromic substrings. Otherwise, return _false.​​​​​

A string is said to be palindrome if it the same string when reversed.

 

Example 1:

Input: s = "abcbdd"
Output: true
Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.

Example 2:

Input: s = "bcbddxy"
Output: false
Explanation: s cannot be split into 3 palindromes.

 

Constraints:

  • 3 <= s.length <= 2000
  • s​​​​​​ consists only of lowercase English letters.

Solutions

Solution 1

class Solution:
  def checkPartitioning(self, s: str) -> bool:
    n = len(s)
    g = [[True] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
      for j in range(i + 1, n):
        g[i][j] = s[i] == s[j] and (i + 1 == j or g[i + 1][j - 1])
    for i in range(n - 2):
      for j in range(i + 1, n - 1):
        if g[0][i] and g[i + 1][j] and g[j + 1][-1]:
          return True
    return False
class Solution {
  public boolean checkPartitioning(String s) {
    int n = s.length();
    boolean[][] g = new boolean[n][n];
    for (var e : g) {
      Arrays.fill(e, true);
    }
    for (int i = n - 1; i >= 0; --i) {
      for (int j = i + 1; j < n; ++j) {
        g[i][j] = s.charAt(i) == s.charAt(j) && (i + 1 == j || g[i + 1][j - 1]);
      }
    }
    for (int i = 0; i < n - 2; ++i) {
      for (int j = i + 1; j < n - 1; ++j) {
        if (g[0][i] && g[i + 1][j] && g[j + 1][n - 1]) {
          return true;
        }
      }
    }
    return false;
  }
}
class Solution {
public:
  bool checkPartitioning(string s) {
    int n = s.size();
    vector<vector<bool>> g(n, vector<bool>(n, true));
    for (int i = n - 1; i >= 0; --i) {
      for (int j = i + 1; j < n; ++j) {
        g[i][j] = s[i] == s[j] && (i + 1 == j || g[i + 1][j - 1]);
      }
    }
    for (int i = 0; i < n - 2; ++i) {
      for (int j = i + 1; j < n - 1; ++j) {
        if (g[0][i] && g[i + 1][j] && g[j + 1][n - 1]) {
          return true;
        }
      }
    }
    return false;
  }
};
func checkPartitioning(s string) bool {
  n := len(s)
  g := make([][]bool, n)
  for i := range g {
    g[i] = make([]bool, n)
    for j := range g[i] {
      g[i][j] = true
    }
  }
  for i := n - 1; i >= 0; i-- {
    for j := i + 1; j < n; j++ {
      g[i][j] = s[i] == s[j] && (i+1 == j || g[i+1][j-1])
    }
  }
  for i := 0; i < n-2; i++ {
    for j := i + 1; j < n-1; j++ {
      if g[0][i] && g[i+1][j] && g[j+1][n-1] {
        return true
      }
    }
  }
  return false
}

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

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

发布评论

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