Palindrome Partitioning II--LeetCode

冷不防 2022-08-07 12:56 27阅读 0赞

题目:

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

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

思路:和上面一题一样,找出所有的可能,从中找出分割次数最少的。

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. bool check(string& str,int begin,int end)
  6. {
  7. int i = begin ;
  8. int j = end;
  9. for(;i<=j;i++,j--)
  10. if(str[i] != str[j])
  11. return false;
  12. return true;
  13. }
  14. void helper(string& str,int begin,int end,vector<int>& pos,int& count)
  15. {
  16. int i,j,k;
  17. if(begin > end)
  18. {
  19. int k =0;
  20. for(j=0;j<pos.size();j++)
  21. {
  22. if(pos[j] != -1 && j != pos.size()-1)
  23. {
  24. k++;
  25. pos[j] = -1;
  26. }
  27. /*
  28. cout<<str[j];
  29. if(pos[j] != -1)
  30. {
  31. cout<<",";
  32. pos[j] = -1;
  33. } */
  34. }
  35. if(k < count)
  36. count = k;
  37. // cout<<endl;
  38. }
  39. for(i= begin;i<=end;i++)
  40. {
  41. if(check(str,begin,i))
  42. {
  43. pos[i] = i-begin+1;
  44. helper(str,i+1,end,pos,count);
  45. }
  46. }
  47. }
  48. int PalindromePartition(string& str)
  49. {
  50. if(str.length() == 0)
  51. return 0;
  52. vector<int> pos(str.length(),-1);
  53. int count=str.length()-1;
  54. helper(str,0,str.length()-1,pos,count);
  55. return count;
  56. }
  57. int main()
  58. {
  59. string str("aab");
  60. cout<<PalindromePartition(str);
  61. system("pause");
  62. return 0;
  63. }

其实这个题目比上一个题目更加简单,因为之间看分割的最少次数,同样的分割方式,只不过需要关注的是分割的最少次数

发表评论

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

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

相关阅读