Merge pull request #647 from ironartisan/master

添加131.分割回文串python3版本
This commit is contained in:
程序员Carl
2021-08-26 11:15:12 +08:00
committed by GitHub
5 changed files with 82 additions and 8 deletions

View File

@ -21,18 +21,27 @@ n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
输出:
解法 1
[
[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
解法 2
["..Q.",
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
提示:

View File

@ -22,15 +22,22 @@ n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并
示例:
输入: 4
输出: 2
解释: 4 皇后问题存在如下两个不同的解法。
解法 1
[
 [".Q..",  // 解法 1
 [".Q..",
  "...Q",
  "Q...",
  "..Q."],
 ["..Q.",  // 解法 2
解法 2
 ["..Q.",
  "Q...",
  "...Q",
  ".Q.."]

View File

@ -309,7 +309,35 @@ class Solution {
```
python版本
```python
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
path = [] # 存放分割后的字符
# 判断数组中的数字是否合法
def isValid(p):
if p == '0': return True # 解决"0000"
if p[0] == '0': return False
if int(p) > 0 and int(p) <256: return True
return False
def backtrack(s, startIndex):
if len(s) > 12: return # 字符串长度最大为12
if len(path) == 4 and startIndex == len(s): # 确保切割完且切割后的长度为4
res.append(".".join(path[:])) # 字符拼接
return
for i in range(startIndex, len(s)):
if len(s) - startIndex > 3*(4 - len(path)): continue # 剪枝,剩下的字符串大于允许的最大长度则跳过
p = s[startIndex:i+1] # 分割字符
if isValid(p): # 判断字符是否有效
path.append(p)
else: continue
backtrack(s, i + 1) # 寻找i+1为起始位置的子串
path.pop()
backtrack(s, 0)
return res
```
```python
class Solution(object):
def restoreIpAddresses(self, s):

View File

@ -292,7 +292,8 @@ class Solution {
```
Python
```py
```python
# 版本一
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
@ -310,7 +311,36 @@ class Solution:
return res
```
```python
# 版本二
class Solution:
def partition(self, s: str) -> List[List[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 backtrack(s, startIndex):
if startIndex >= len(s): # 如果起始位置已经大于s的大小说明已经找到了一组分割方案了
res.append(path[:])
return
for i in range(startIndex, len(s)):
p = s[startIndex:i+1] # 获取[startIndex,i+1]在s中的子串
if isPalindrome(p): # 是回文子串
path.append(p)
else: continue #不是回文,跳过
backtrack(s, i + 1)
path.pop() #回溯过程弹出本次已经填在path的子串
backtrack(s, 0)
return res
```
Go
> 注意切片go切片是披着值类型外衣的引用类型

View File

@ -184,7 +184,7 @@ public:
这份代码在leetcode上提交要比版本一耗时要好的多。
**所以正如在[哈希表:总结篇!(每逢总结必经典)](https://programmercarl.com/哈希表总结.html)中说的那样数组setmap都可以做哈希表而且数组干的活map和set都能干但如数值范围小的话能用数组尽量用数组**
**所以正如在[哈希表:总结篇!(每逢总结必经典)](https://programmercarl.com/哈希表总结.html)中说的那样数组setmap都可以做哈希表而且数组干的活map和set都能干但如数值范围小的话能用数组尽量用数组**