Python算法题集_分割回文串

本文为Python算法题集之一的代码示例

题131:分割回文串

1. 示例说明

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

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

    示例 1:

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

    示例 2:

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

    提示:

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

2. 题目解析

- 题意分解

  1. 本题是检测字符串中的所有回文串
  2. 基本的设计思路是通过回溯法遍历本字符串所有可能子串,检测是否回文

- 优化思路

  1. 通常优化:减少循环层次

  2. 通常优化:增加分支,减少计算集

  3. 通常优化:采用内置算法来提升计算速度

  4. 分析题目特点,分析最优解

    1. 回溯算法过程中进行参数数量空值,并尝试切换值传递、引用传递,回退方面可以尝试参数回退、堆栈回退

    2. 回文检测算法可以想想不同实现方式


- 测量工具

  • 本地化测试说明:LeetCode网站测试运行时数据波动很大【可把页面视为功能测试】,因此需要本地化测试解决数据波动问题
  • CheckFuncPerf(本地化函数用时和内存占用测试模块)已上传到CSDN,地址:Python算法题集_检测函数用时和内存占用的模块
  • 本题本地化超时测试用例自己生成,详见章节【最优算法】,代码文件包含在【相关资源】中

3. 代码展开

1) 标准求解【参数回退回溯+单行回文检测】

使用参数回退实现回溯,回文检测采用单行代码

页面功能测试,马马虎虎,超过39%在这里插入图片描述

import CheckFuncPerf as cfp

class Solution:
 def partition_base(self, s):
     def backtrack(s, result, path):
         if not s:
             result.append(path)
             return
         for iIdx in range(1, len(s) + 1):
             if s[:iIdx] == s[:iIdx][::-1]:
                 backtrack(s[iIdx:], result, path + [s[:iIdx]])
     result = []
     backtrack(s, result, [])
     return result

aSolution = Solution()
result = cfp.getTimeMemoryStr(aSolution.partition_base, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))

# 运行结果
函数 partition_base 的运行时间为 5269.33 ms;内存使用量为 212320.00 KB 执行结果 = 601812

2) 改进版一【参数回退回溯+lambda回文检测】

使用参数回退实现回溯,回文检测改为lambda函数

页面功能测试,性能一般,超过75%在这里插入图片描述

import CheckFuncPerf as cfp

class Solution:
 def partition_ext1(self, s):
     isPalindrome = lambda s: s == s[::-1]
     def backtrack(s, result, path):
         if not s:
             result.append(path)
             return
         for i in range(1, len(s) + 1):
             if isPalindrome(s[:i]):
                 backtrack(s[i:], result, path + [s[:i]])
     result = []
     backtrack(s, result, [])
     return result

aSolution = Solution()
result = cfp.getTimeMemoryStr(aSolution.partition_ext1, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))

# 运行结果
函数 partition_ext1 的运行时间为 4536.02 ms;内存使用量为 212004.00 KB 执行结果 = 601812

3) 改进版二【参数回退回溯+函数回文检测】

使用参数回退实现回溯,回文检测改为函数,并在函数中逐步进行终止判断

页面功能测试,性能一般,超过73%在这里插入图片描述

import CheckFuncPerf as cfp

class Solution:
 def partition_ext2(self, s):
     def isPalindrome(s):
         ileft, iright = 0, len(s) - 1
         while ileft < iright:
             if s[ileft] != s[iright]:
                 return False
             ileft += 1
             iright -= 1
         return True
     def backtrack(s, result, path):
         if not s:
             result.append(path)
             return
         for iIdx in range(1, len(s) + 1):
             if isPalindrome(s[:iIdx]):
                 backtrack(s[iIdx:], result, path + [s[:iIdx]])
     result = []
     backtrack(s, result, [])
     return result

aSolution = Solution()
result = cfp.getTimeMemoryStr(aSolution.partition_ext2, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))
 
# 运行结果
函数 partition_ext2 的运行时间为 5435.21 ms;内存使用量为 208024.00 KB 执行结果 = 601812

4) 改进版三【堆栈回退回溯+函数回文检测】

使用参数回退实现回溯,回文检测改为函数,并在函数中进行终止判断

页面功能测试,马马虎虎,超过34%在这里插入图片描述

import CheckFuncPerf as cfp

class Solution:
 def partition_ext3(self, s):
     result, path = [], []
     def isPalindrome(s):
         ileft, iright = 0, len(s) - 1
         while ileft < iright:
             if s[ileft] != s[iright]:
                 return False
             ileft += 1
             iright -= 1
         return True
     def back_track(s, index):
         if index == len(s):
             result.append(path[:])
             return
         for iIdx in range(index, len(s)):
             if isPalindrome(s[index:iIdx+1]):
                 path.append(s[index:iIdx+1])
                 back_track(s, iIdx+1)
                 path.pop()
     back_track(s, 0)
     return result

aSolution = Solution()
result = cfp.getTimeMemoryStr(aSolution.partition_ext3, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))

# 运行结果
函数 partition_ext3 的运行时间为 5541.26 ms;内存使用量为 207644.00 KB 执行结果 = 601812

4. 最优算法

根据本地日志分析,最优算法为第2种方式【参数回退回溯+lambda回文检测】partition_ext1

本题大概有以下结论:

  1. 回文检测中,函数和Python代码直接执行性能相近,lambda函数性能最好
  2. 参数回退和堆栈回退实现的回溯算法性能相近
stemplete, ilen = 'abcdeedcba', 5
checkstr = ''.join([stemplete] * ilen)
aSolution = Solution()
result = cfp.getTimeMemoryStr(aSolution.partition_base, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))
result = cfp.getTimeMemoryStr(aSolution.partition_ext1, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))
result = cfp.getTimeMemoryStr(aSolution.partition_ext2, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))
result = cfp.getTimeMemoryStr(aSolution.partition_ext3, checkstr)
print(result['msg'], '执行结果 = {}'.format(len(result['result'])))

# 算法本地速度实测比较
函数 partition_base 的运行时间为 5269.33 ms;内存使用量为 212320.00 KB 执行结果 = 601812
函数 partition_ext1 的运行时间为 4536.02 ms;内存使用量为 212004.00 KB 执行结果 = 601812
函数 partition_ext2 的运行时间为 5435.21 ms;内存使用量为 208024.00 KB 执行结果 = 601812
函数 partition_ext3 的运行时间为 5541.26 ms;内存使用量为 207644.00 KB 执行结果 = 601812

5. 相关资源

本文代码已上传到CSDN,地址:Python算法题源代码_LeetCode(力扣)_分割回文串)

一日练,一日功,一日不练十日空

may the odds be ever in your favor ~

  • 24
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长孤秋落

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值