LeetCode 高级 - 分割回文串
2018-07-27 22:09
239 查看
版权声明:本文出自 whdAlive 的博客,转载必须注明出处 https://blog.csdn.net/whdAlive/article/details/81254975
分割回文串
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ]
分析
解题思路就是 DFS,用一个boolean[] 数组记录当前可分割的位置,每一次深搜的过程都是找下一个可以分割的位置。
为了更容易理解,通过代码简单输出执行的流程(代码中 注释掉的输出部分),建议自己捋清楚整个算法的执行流程,以便举一反三,下面给出我整理的流程(只给思路,不涉及分割位置数组的细节)。
实际上对于 s=”aab” 而言,就是三层递归,每层递归向后找能分割的位置:
- 层1:从下标 0~2 寻找分割位置,对应子串为 aab
- 层2:从下标 x~2(x为 最外层传入的下标 和 1 中的大值) 寻找分割位置,对应子串为 ab 或 b
- 层3:从下标 y~2(y为 中间层传入的下标 和 2 中的大者 ) 寻找分割位置,对应子串为 b 或 无
流程:
- 最开始会深搜到 层3,将 s 分割为 “a”,”a”,”b”,并记录此分割方案 [“a”,”a”,”b”]
- 回溯到 层2, “a” 不动,判断 “ab” 不满足(即考虑 [“a”,”ab”] 方案)
- 回溯到 层1,判断”aa” 满足
- 进入 层2,判断 “b” 满足,此时记录此种方案 [“aa”,”b”]
- 回溯到 层1,”aa”的基础上加上 “b”,判断 “aab” 不满足
- 层1 遍历结束,整个流程结束。
代码
class Solution { List results; public List<List<String>> partition(String s) { results = new ArrayList<ArrayList<String>>(); boolean[] cut = new boolean[s.length()]; find(s,0,cut); return results; } private void find(String s,int index,boolean[] cut){ if(index == s.length()){ List<String> temp = new ArrayList<String>(); int begin = 0,last = 0; while(last < s.length()){ if(cut[last]){ temp.add(s.substring(begin,last+1)); begin = last+1; } last++; } results.add(temp); } //向右找回文字符串。 for(int i=index;i<s.length();i++){ if(isPalindrome(s,index,i)){ cut[i] = true; /* System.out.println("进入下一层"); System.out.println("index:"+index+";i:"+i); System.out.println("cut:"+cut[0]+","+cut[1]+","+cut[2]); */ find(s,i+1,cut); cut[i]=false; /* System.out.println("返回上一层"); System.out.println("index:"+index+";i:"+i); System.out.println("cut:"+cut[0]+","+cut[1]+","+cut[2]); */ } } } //判断是否为回文字符串 private boolean isPalindrome(String s,int begin,int last){ while(begin < last && s.charAt(begin) == s.charAt(last)){ begin++; last--; } return begin >= last; } }阅读更多
相关文章推荐
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- LeetCode-----回文串的最小分割
- 【LeetCode】Longest Palindrome(最长回文串) - Easy
- LeetCode-Palindrome Partitioning II-回文分割-DP优化
- lintcode-分割回文串-136
- [LeetCode 131] - 回文分割(Palindrome Partitioning)
- [LeetCode] Split Array into Consecutive Subsequences 将数组分割成连续子序列
- [LeetCode] 409. 最长回文串
- 1、分割回文串——回溯法
- Leetcode 409. Longest Palindrome 构造最长回文串 解题报告
- [LeetCode] 214. Shortest Palindrome 最短回文串
- 分割回文串 II-LintCode
- Longest Palindromic Substring (最长回文串)【面试算法leetcode】
- leetcode 最长回文串
- leetcode 434. Number of Segments in a String 按照空格分割字符串 + C++的stringstream的一个很好应用示范
- LeetCode-Palindrome Partitioning-回文分割
- leetcode 434.Number of Segments in a String(easy)[分割字符串]
- LeetCode 分割整数数组,分割为两部分的和相等
- LeetCode | Valid Palindrome(有效的回文串)
- [LeetCode] Palindrome Partitioning II 拆分回文串之二