[LeetCode 131] Palindrome Partitioning

90 篇文章 0 订阅

原文地址:http://blog.csdn.net/zhanghaodx082/article/details/24184195

题目大意:

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"]
  ]

我:要开始研究树跟图的算法了
意思就是:给定一个字符串s,把s划分成回文串。找出所有可能的情况。
做题思路:
1,首先要有一个判断字符串是否是回文的函数。容易实现,字符串从两边同时往中间走,看字符是否相同;
2,深度优先搜索思想对字符串进行遍历。得到结果。例如,s = "abacd"; 需要对“a”“ad”“aba”“abac”“abacd”进行深度优先搜索。深度搜索的过程如下:先选“a”,发现“a”是回文,则深度遍历“bacd”,继续深度遍历,“b”也是回文,深度遍历“acd”,继续下去;
  同时,深度遍历“a”的同时,也需要深度遍历“ab”,“aba”,“abac”,“abacd”。发现只有“aba”是回文,所以继续深度搜索“cd”。
代码如下:

 
 
  1. class Solution {  
  2.     public:  
  3.         vector< vector<string> > partition(string s){  
  4.             string::size_type length = s.size();  
  5.             if(length == 0){  
  6.                 output.clear();  
  7.                 return output;  
  8.             }  
  9.             else{  
  10.                 output.clear();  
  11.                 temper_result.clear();  
  12.                 dfs(0,length,s);  
  13.                 return output;  
  14.             }  
  15.         }  
  16.         bool ifpalindrome(string& s){  
  17.             int i = 0, j = s.length()-1;  
  18.             while(i < j){  
  19.                 if(s[i] != s[j]){  
  20.                     return false;  
  21.                 }  
  22.                 i++;  
  23.                 j--;  
  24.             }  
  25.             return true;  
  26.         }  
  27.         void dfs(int begin, int length, string& s){  
  28.             if(begin == length){  
  29.                 output.push_back(temper_result);  
  30.             }  
  31.             else{  
  32.                 int i;  
  33.                 for(i=begin;i<length;i++){  
  34.                     string mm =s.substr(begin,i-begin+1);  
  35.                     if(ifpalindrome(mm)){  
  36.                         temper_result.push_back(mm);  
  37.                         dfs(i+1,length,s);  
  38.                         temper_result.pop_back();  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.     private:  
  44.         vector< vector<string> > output;  
  45.         vector<string> temper_result;  
  46. };  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值