分割回文串
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 66 ms, 内存: 30.3 MB
// Java Stream solution for the palindrome partitioning problem
// This solution uses Java Streams for a more functional approach
// We use the same logic as the previous solution but with Streams
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PalindromePartitioningStream {
public List<List<String>> partition(String s) {
return partition(s, 0);
}
private List<List<String>> partition(String s, int start) {
if (start == s.length()) {
List<List<String>> result = new ArrayList<>();
result.add(new ArrayList<>());
return result;
}
return IntStream.range(start, s.length())
.filter(i -> isPalindrome(s, start, i))
.mapToObj(i -> partition(s, i + 1).stream()
.peek(list -> list.add(0, s.substring(start, i + 1)))
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
}
private boolean isPalindrome(String s, int low, int high) {
while (low < high) {
if (s.charAt(low++) != s.charAt(high--)) return false;
}
return true;
}
public static void main(String[] args) {
PalindromePartitioningStream solution = new PalindromePartitioningStream();
System.out.println(solution.partition("google"));
System.out.println(solution.partition("aab"));
System.out.println(solution.partition("a"));
}
}
解释
方法:
题解采用了动态规划的方法来解决问题。首先,定义一个列表 `ans` 来存储从字符串起始到每个位置的所有可能的回文分割列表。`ans[i]` 存储的是对字符串 `s[0:i]` 的所有回文分割方式。对于每个字符 `s[i]`,通过内部循环检查以 `j` 开始到 `i` 结束的子串 `s[j:i+1]` 是否为回文串。如果是回文,那么将 `ans[j]` 中的每个分割方案加上这个回文串,形成新的分割方案,并加到临时列表 `tmp` 中。最后将 `tmp` 加入到 `ans` 中。整个过程结束后,`ans[-1]` 将包含对整个字符串 `s` 的所有回文分割方案。
时间复杂度:
O(n^3)
空间复杂度:
O(n*2^n)
代码细节讲解
🦆
在解决方案中,为什么选择使用动态规划而不是其它算法?
▷🦆
在动态规划的过程中,如何保证`ans[j]`里存储的方案都是有效的回文分割?
▷🦆
对于子串`s[j:i+1]`的回文检查为什么使用`cur == cur[::-1]`,这种方法的效率如何?
▷