leetcode之Palindrome Partitioning

题目大意:

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”。
代码如下:
class Solution {
	public:
		vector< vector<string> > partition(string s){
			string::size_type length = s.size();
			if(length == 0){
				output.clear();
				return output;
			}
			else{
				output.clear();
				temper_result.clear();
				dfs(0,length,s);
				return output;
			}
		}
		bool ifpalindrome(string& s){
			int i = 0, j = s.length()-1;
			while(i < j){
				if(s[i] != s[j]){
					return false;
				}
				i++;
				j--;
			}
			return true;
		}
		void dfs(int begin, int length, string& s){
			if(begin == length){
				output.push_back(temper_result);
			}
			else{
				int i;
				for(i=begin;i<length;i++){
					string mm =s.substr(begin,i-begin+1);
					if(ifpalindrome(mm)){
						temper_result.push_back(mm);
						dfs(i+1,length,s);
						temper_result.pop_back();
					}
				}
			}
		}
	private:
		vector< vector<string> > output;
		vector<string> temper_result;
};


你可能感兴趣的:(LeetCode,C++,算法)