Leetcode 刷题第26天 | 131,93

Leetcode 131 分割回文串

题目:

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = “aab”
输出:[[“a”,“a”,“b”],[“aa”,“b”]]
示例 2:
输入:s = “a”
输出:[[“a”]]
提示:

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

算法思想:

采用回溯算法。

  • 回溯函数模板返回值以及参数
    path:记录当前路径上的节点
    result:记录所有满足条件的组合
    startIndex:切割字符串,切割过后的字符串肯定不能再切割了,所以采用startIndex随着切割的进度逐渐增长。
  • 回溯函数终止条件
    当startIndex与字符串的长度相等的时候,停止切割,表示当前迭代到了最后。为什么是startIndex?仔细想,startIndex表示当前字符的下一个字符,正好是切割的分割点。
  • 单层搜索逻辑
    首先判断切割的字符串是不是回文串(这也是区别于之前组合之和的地方)
    • path中加入节点
    • 递归加入下一个节点
    • path中出栈

如果不是:
continue或不用处理。ps:切记用break;如果用break,efe这种例子就回通不过。

代码实现:

class Solution:
    def partition(self, s: str):
        path = []
        result = []
        startIndex = 0
        self.backtracing(s, path, result, startIndex)
        return result

    def backtracing(self, s, path, result, startIndex):
    	# 终止条件
        if len(s) == startIndex:
            result.append(copy.deepcopy(path))
            return 
        
        for i in range(startIndex, len(s)):
            print(startIndex, i)
            # 这里是与组合之和最不相同的地方,之前的题目都是直接处理节点,现在要判断一下。
            if self.is_palindrome(s[startIndex: i+1]):
                path.append(s[startIndex: i+1])
                self.backtracing(s, path, result, i+1)
                path.pop()
        return result

    def is_palindrome(self, s):
    	# 判断回文串第一种写法
        # i = start
        # j = end
        # while i < j:
        #     if s[i] != s[j]:
        #         return False
        #     i = i + 1
        #     j = j - 1
        # return True

        # 判断回文串第二种写法
        return s == s[::-1]

Leetcode 93 复原IP地址

题目:

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。
例如:“0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 ‘.’ 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
示例 2:
输入:s = “0000”
输出:[“0.0.0.0”]
示例 3:
输入:s = “101023”
输出:[“1.0.10.23”,“1.0.102.3”,“10.1.0.23”,“10.10.2.3”,“101.0.2.3”]
提示:
1 <= s.length <= 20
s 仅由数字组成

算法描述:

采用回溯算法。

  • 回溯函数模板返回值以及参数
    path:记录当前路径上的节点
    result:记录所有满足条件的组合
    startIndex:某个位置上取过后,不在取,符合ip地址的直觉。
  • 回溯函数终止条件
    当path中包含四个元素,且元素的长度之和恰好等于题目中输入的字符串的长度,收集结果,返回
  • 单层搜索逻辑
    首先判断数字范围是否有效
    1. path中加入节点
    2. 递归加入下一个节点
    3. path中出栈
    无效:
    结束当前迭代的循环

代码实现:

class Solution:
    def restoreIpAddresses(self, s):
        result = []
        path = []
        # 判断 给定的字符串是否可以合理切割
        if len(s) <= 3 or len(s) > 12:
            return result
        self.backtracing(s, 0, path, result)
        return result

    def backtracing(self, s, start_index, path, result):
        # 对于ip地址,逗点个数是3的情况下
        # if point_num == 3:
        #     if self.is_valid(s, start_index, len(s)-1):
        #         current += s[start_index:]
        #         result.append(current)
        #     return
        if len(path) == 4 and sum([len(i) for i in path]) == len(s):
            # if  self.is_valid(s, start_index, len(s)-1):
            result.append(".".join(copy.deepcopy(path)))
            return

        for i in range(start_index, len(s)):
            if self.is_valid(s, start_index, i):
                sub = s[start_index: i+1]
                path.append(sub)
                self.backtracing(s, i+1, path, result)
                path.pop()
            else:	# 问题:为什么这里break可以,会不会是pass掉一些情况的组合?
                break

    def is_valid(self, s, start, end):
        # 0 开头的数字不合法
        if s[start] == '0' and start != end:
            return False
        
        # 判断是否遇到非法字符,是否超过255
        num = 0
        for i in range(start, end+1):
            if not s[i].isdigit():
                return False
            num = num * 10 + int(s[i])
            if num > 255:
                return False
        return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值