码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Palindrome Partitioning

时间:2014-07-28 19:17:14      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   art   div   

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"]
  ]
 注意下面的例子:                                                                          
Input: "fff"
Expected: [["f","f","f"],["f","ff"],["ff","f"],["fff"]]

 

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        if(s.size()<1)
            return res;
        vector<string> partition;
        addPalindrome(s,0,partition,res);
        return res;
    }
private:
    void addPalindrome(string s,int start,vector<string> &partition,vector<vector<string> >&res){
        if(start == s.size()){
            res.push_back(partition);
            return;
        }
        for(int i = start+1;i<=s.size();i++){
            string str = s.substr(start,i-start);
            if(isPalindrome(str)){
                partition.push_back(str);
                addPalindrome(s,i,partition,res);
                partition.pop_back();
            }//end if
        }//end for

    }

    bool isPalindrome(string str){
        int left = 0;
        int right = str.size()-1;
        while(left<right){
            if(str[left]!=str[right])
                return false;
            left++;
            right--;
        }//end while
       return true;
    }
};

 方法:DFS!

[LeetCode] Palindrome Partitioning,布布扣,bubuko.com

[LeetCode] Palindrome Partitioning

标签:style   blog   color   os   io   for   art   div   

原文地址:http://www.cnblogs.com/Xylophone/p/3872720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!