LeetCode: Palindrome Partition

题目

https://oj.leetcode.com/problems/palindrome-partitioning/


分析

DFS来解决这个问题。


代码

class Solution
{
public:
	vector> partition(string s)
	{
		if (s.empty())
			return res;

		dfs(s, 0);

		return res;
	}

	void dfs(const string &s, int index)
	{
		if (index == s.size())
			res.push_back(solution);
		else
		{
			for (int i = index; i < s.size(); i++)
			{
				string substr = s.substr(index, i-index+1);
				if (isPalindrome(substr))
				{
					solution.push_back(substr);
					dfs(s, i+1);
					solution.pop_back();
				}
			}
		}
	}
		
	bool isPalindrome(const string &s)
	{
		int left = 0;
		int right = s.size() - 1;

		while (left <= right)
		{
			if (s[left] != s[right])
				return false;
			left++;
			right--;
		}
		return true;
	}

	vector> res;
	vector solution;
};


参考

http://fisherlei.blogspot.com/2013/03/leetcode-palindrome-partitioning.html

你可能感兴趣的:(OJ题解,LeetCode题解)