法1:DFS+双指针
Python
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = list()
tmp = list()
self.dfs(0, s, tmp, res)
return res
def dfs(self, idx, s, tmp, res):
if idx == len(s):
res.append(tmp.copy())
for i in range(idx, len(s)):
if self.is_valid(s, idx, i):
tmp.append(s[idx:i+1])
self.dfs(i+1, s, tmp, res)
tmp.pop()
def is_valid(self, s, i, j) -> bool:
if i < 0 or i >= len(s) or j < 0 or j >= len(s) or i > j:
return False
l = i
r = j
while l <= r:
if s[l] == s[r]:
l += 1
r -= 1
else:
return False
return True
Java
必须掌握基础方法!
注意:使用ArrayList删除尾元素比LinkedList要快很多!!!
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s.length() == 0) {
return res;
}
List<String> tmp = new ArrayList<>();
dfs(s, 0, tmp, res);
return res;
}
public void dfs(String s, int startIndex, List<String> tmp, List<List<String>> res) {
if (startIndex == s.length()) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = startIndex; i < s.length(); ++i) {
if (!valid(s, startIndex, i)) {
continue;
}
tmp.add(s.substring(startIndex, i + 1));
dfs(s, i + 1, tmp, res);
tmp.remove(tmp.size() - 1);
}
}
public boolean valid(String s, int startIndex, int endIndex) {
while (startIndex <= endIndex) {
char left = s.charAt(startIndex);
char right = s.charAt(endIndex);
if (left != right) {
return false;
}
++startIndex;
--endIndex;
}
return true;
}
}
法2:DFS+回文串判断预处理
主要优化回文串判断部分
Python
class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
judge = [[False]*n for _ in range(n)]
for i in range(n):
judge[i][i] = True
for i in range(n-2, -1, -1):
for j in range(i+1, n):
if s[i] == s[j] and (j-i == 1 or judge[i+1][j-1]):
judge[i][j] = True
else:
judge[i][j] = False
res = list()
tmp = list()
self.dfs(0, s, tmp, res, judge)
return res
def dfs(self, idx, s, tmp, res, judge):
if idx == len(s):
res.append(tmp.copy())
for i in range(idx, len(s)):
if judge[idx][i]:
tmp.append(s[idx: i+1])
self.dfs(i+1, s, tmp, res, judge)
tmp.pop()
Java
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
int n = s.length();
boolean[][] dp = new boolean[n][n]; // dp[i][j]表示s[i:j]之间是回文串
for (int i = 0; i < n; ++i) {
dp[i][i] = true;
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j - i == 1 || dp[i + 1][j - 1]);
}
}
List<String> tmp = new ArrayList<>();
dfs(s, res, tmp, dp, 0);
return res;
}
public void dfs(String s, List<List<String>> res, List<String> tmp, boolean[][] dp, int curInx) {
if (curInx == s.length()) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = curInx; i < s.length(); ++i) {
if (dp[curInx][i]) {
tmp.add(s.substring(curInx, i + 1));
dfs(s, res, tmp, dp, i + 1);
tmp.remove(tmp.size() - 1);
}
}
}
}