leetcode 131. Palindrome Partitioning 按照index做DFS深度优先遍历

Bertha 。 2022-06-08 05:36 256阅读 0赞

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = “aab”,
Return

[
[“aa”,”b”],
[“a”,”a”,”b”]
]

本题是找到所有的回文子串,就是按照index做一下深度优先遍历,但是注意剪枝。

这道题最直接的方法就是寻找到所有的子串组合,然后判断是否是满足回文要求,所以直接DFS深度优先遍历找到所有的可能即可,不需要想的太复杂,这是一道很经典的按照index的DFS即可

建议和leetcode 680. Valid Palindrome II 去除一个字符的回文字符串判断 + 双指针 一起学习

代码如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /*
  4. * 本题考查回溯算法。从下标0开始遍历字符串,一旦在下标 i 找到回文子字符串,
  5. * 那么就把下标从 0 到 i 的子字符串加入temp中,继续从下标 i 接着往下找,一旦
  6. * curIndex等于字符串长度,那么就把temp加入到result中。如果一直到最后都没找到
  7. * 回文子字符串,那么就进行剪枝:
  8. *
  9. * 这个题值得反思回溯算法, 需要好好的想一下
  10. * */
  11. public class Solution
  12. {
  13. List<List<String>> res = new ArrayList<>();
  14. public List<List<String>> partition(String s)
  15. {
  16. if(s==null || s.length()<=0 )
  17. return res;
  18. List<String> one = new ArrayList<>();
  19. dfs(one,s,0);
  20. return res;
  21. }
  22. public void dfs(List<String> one, String s, int index)
  23. {
  24. if(index == s.length())
  25. {
  26. res.add(new ArrayList<>(one));
  27. return ;
  28. }else
  29. {
  30. for(int i=index+1;i<=s.length();i++)
  31. {
  32. String tmp = s.substring(index,i);
  33. if(isPalindrome(tmp))
  34. {
  35. one.add(tmp);
  36. dfs(one, s, i);
  37. one.remove(one.size()-1);
  38. }
  39. }
  40. }
  41. }
  42. private boolean isPalindrome(String s)
  43. {
  44. int begin=0,end=s.length()-1;
  45. while(begin<end)
  46. {
  47. if(s.charAt(begin)!=s.charAt(end))
  48. return false;
  49. begin++;
  50. end--;
  51. }
  52. return true;
  53. }
  54. }

下面是C++的做法,就是做一个DFS深度优先遍历即可完成

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <string>
  5. using namespace std;
  6. class Solution
  7. {
  8. public:
  9. vector<vector<string>> res;
  10. vector<vector<string>> partition(string s)
  11. {
  12. vector<string> one;
  13. getAll(s, 0, one);
  14. return res;
  15. }
  16. void getAll(string s,int index,vector<string>& one)
  17. {
  18. if (index >= s.length())
  19. {
  20. res.push_back(one);
  21. return;
  22. }
  23. else
  24. {
  25. for (int len = 1; len + index <= s.length(); len++)
  26. {
  27. string tmp = s.substr(index, len);
  28. if (isVaild(tmp))
  29. {
  30. one.push_back(tmp);
  31. getAll(s, index + len, one);
  32. one.erase(one.end() - 1);
  33. }
  34. }
  35. }
  36. }
  37. bool isVaild(string s)
  38. {
  39. int i = 0,j = s.length() - 1;
  40. while (i < j)
  41. {
  42. if (s[i] != s[j])
  43. return false;
  44. else
  45. {
  46. i++;
  47. j--;
  48. }
  49. }
  50. return true;
  51. }
  52. };

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读