From 4b0982e681e72081752843e8df83c0ceec1b543a Mon Sep 17 00:00:00 2001 From: Liu Cheng <32453247+Falldio@users.noreply.github.com> Date: Fri, 7 Apr 2023 14:29:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00132.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E4=B8=B2II=E7=9A=84Golang=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0132.分割回文串II.md | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0132.分割回文串II.md b/problems/0132.分割回文串II.md index eb0e39fb..9b164dfb 100644 --- a/problems/0132.分割回文串II.md +++ b/problems/0132.分割回文串II.md @@ -289,7 +289,45 @@ class Solution: ## Go ```go +func minCut(s string) int { + isValid := make([][]bool, len(s)) + for i := 0; i < len(isValid); i++ { + isValid[i] = make([]bool, len(s)) + isValid[i][i] = true + } + for i := len(s) - 1; i >= 0; i-- { + for j := i + 1; j < len(s); j++ { + if s[i] == s[j] && (isValid[i + 1][j - 1] || j - i == 1) { + isValid[i][j] = true + } + } + } + dp := make([]int, len(s)) + for i := 0; i < len(s); i++ { + dp[i] = math.MaxInt + } + for i := 0; i < len(s); i++ { + if isValid[0][i] { + dp[i] = 0 + continue + } + for j := 0; j < i; j++ { + if isValid[j + 1][i] { + dp[i] = min(dp[i], dp[j] + 1) + } + } + } + return dp[len(s) - 1] +} + +func min(i, j int) int { + if i < j { + return i + } else { + return j + } +} ``` ## JavaScript