zoukankan      html  css  js  c++  java
  • 0131分割回文串 Marathon

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

    回文串 是正着读和反着读都一样的字符串。

    示例 1:

    输入:s = "aab"
    输出:[["a","a","b"],["aa","b"]]
    示例 2:

    输入:s = "a"
    输出:[["a"]]

    提示:

    1 <= s.length <= 16
    s 仅由小写英文字母组成

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/palindrome-partitioning

    python

    # 分割回文串
    
    class Solution:
        def partition(self, s:str) -> [[str]]:
            res = []
            path = []
            def isPalindrome(s):
                n = len(s)
                i, j = 0, n-1
                while i<j:
                    if s[i] != s[j]:return False
                    i += 1
                    j -= 1
                return True
    
            def track(s, startIndex):
                # 起始位置已经大于s的大小,说明已经找到一组分割方案
                if startIndex >= len(s):
                    res.append(path[:])
                    return
                for i in range(startIndex, len(s)):
                    # 获取[startIndex:i+1]的子串
                    p = s[startIndex:i+1]
                    if isPalindrome(p):
                        path.append(p)
                    else:
                        continue
                    track(s, i+1)
                    path.pop() # 回溯
    
            track(s,0)
            return res
    
    

    golang

    package backTrack
    
    // 回溯
    func partition(s string) [][]string {
    	var tmpString []string
    	var res [][]string
    	track(s,tmpString,0,&res)
    	return res
    }
    
    func track(s string, tmpstring []string, startIndex int, res *[][]string)  {
    	if startIndex == len(s) { // 到达字符串末尾
    		// 切片拷贝
    		t := make([]string, len(tmpstring))
    		copy(t, tmpstring)
    		*res = append(*res, t)
    	}
    	for i:=startIndex;i<len(s);i++ {
    		if isPalindrome(s, startIndex, i) {
    			tmpstring = append(tmpstring, s[startIndex:i+1])
    		} else {continue}
    		// 递归
    		track(s,tmpstring,i+1,res)
    		// 回溯
    		tmpstring = tmpstring[:len(tmpstring)-1]
    	}
    }
    
    func isPalindrome(s string, startIndex, end int) bool {
    	left := startIndex
    	right := end
    	for left < right {
    		if s[left] != s[right] {
    			return false
    		}
    		left++
    		right--
    	}
    	return true
    }
    
    
  • 相关阅读:
    placement new小结
    template template parameter 模板模板参数
    windows下创建和删除软链接
    gcc下载地址
    map的erase函数小结
    typedef函数指针
    宏定义条件编译中使用多条件
    关于c++模板特例化测试
    tolua使用
    c++多态
  • 原文地址:https://www.cnblogs.com/davis12/p/15586052.html
Copyright © 2011-2022 走看看