From 98209ffa963366e6a2437301604c31006dff9e81 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 22 May 2024 21:46:25 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB131.=20Palindrome=20Partition?= =?UTF-8?q?ing=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/palindrome-partitioning.go | 67 +++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 go/palindrome-partitioning.go diff --git a/go/palindrome-partitioning.go b/go/palindrome-partitioning.go new file mode 100644 index 0000000..4cd92d4 --- /dev/null +++ b/go/palindrome-partitioning.go @@ -0,0 +1,67 @@ +package palindrome_partitioning + +import ( + "slices" +) + +func getPalindromes(s string) [][]bool { + size := len(s) + 1 + + // Create a DP table + palindromes := make([][]bool, size) + for i := range size { + palindromes[i] = make([]bool, size) + } + + // Set the ranges that represent a palindrome + checkPalindromes := func(i, j int) { + if i < 0 || j >= len(s) { + return + } + + for i >= 0 && j < len(s) && s[i] == s[j] { + palindromes[i][j+1] = true + + i -= 1 + j += 1 + } + } + for i, _ := range s { + checkPalindromes(i, i) + checkPalindromes(i, i+1) + } + + return palindromes +} + +func getPartitions(s string, palindromes [][]bool) [][]string { + var partitions [][]string + var currentPartition []string + + var dfs func(int) + dfs = func(i int) { + if i >= len(s) && len(currentPartition) > 0 { + partitions = append(partitions, slices.Clone(currentPartition)) + return + } else if i >= len(s) { + return + } + + for j := len(s); j > i; j-- { + if !palindromes[i][j] { + continue + } + + currentPartition = append(currentPartition, s[i:j]) + dfs(j) + currentPartition = currentPartition[:len(currentPartition)-1] + } + } + + dfs(0) + return partitions +} + +func partition(s string) [][]string { + return getPartitions(s, getPalindromes(s)) +}