leetcode brush title notes (Golang) - 131 Palindrome Partitioning.

131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

func partition(s string) [][]string {
	res := [][]string{}
	dfs(s, 0, []string{}, &res)
	return res
}

func dfs(graph string, curr int, path []string, paths *[][]string) {
	if curr == len(graph) {
		tmp := make([]string, len(path))
		copy(tmp, path)
		*paths = append(*paths, tmp)
		return
	}
	for i := curr; i < len(graph); i++ {
		if !isPalindrome(graph[curr : i+1]) {
			continue
		}
		dfs(graph, i+1, append(path, graph[curr:i+1]), paths)
	}

}

func isPalindrome(s string) bool {
	if s == "" {
		return false
	}
	l := 0
	r := len(s) - 1
	for l < r {
		if s[l] != s[r] {
			return false
		}
		l++
		r--
	}
	return true
}
Published 98 original articles · won praise 0 · Views 1462

Guess you like

Origin blog.csdn.net/weixin_44555304/article/details/104403380