LeetCode-----第131题-----分割回文串

分割回文串

难度:中等

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: "aab"
输出:
[
  ["aa","b"],
  ["a","a","b"]
]

题目分析:

       显然使用回溯算法,将所有分割的可能都尝试一遍,并且判断字符串是否为回文字符串进行剪枝。

       结束条件:当index == n时,所有字符分割完成时

       all station:for循环,全局变量index,每次从index开始遍历,将当前的i+1作为index传入下次递归,因为每次的分割都是在上一次分割的基础上进行的。每次递归前需要检测当前的字符串是否是回文字符串,否则的话不分割。

 

参考代码:

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

		vector<string> temp;
		back_search(res, temp, s, 0, s.size());
		return res;
	}
	void back_search(vector<vector<string>>& res, vector<string> temp, string s, int index, int n)
	{
		//结束条件
		if (index == n)
		{
			res.push_back(temp);
		}
		else{
			for (int i = index; i < s.size(); i++)
			{
				if (check(s, index, i))
				{
					temp.push_back(s.substr(index, i + 1 - index));
					back_search(res, temp, s, i + 1, n);
					temp.pop_back();
				}
			}
		}
	}
	bool check(const string&s, int i, int j)
	{
		if (j < i) return true;
		if (s[i++] == s[j--]) return check(s, i, j);
		else return false;
	}
};

 

参考代码:

//使用子字符串就不需要index了
class Solution {
public:
	vector<vector<string>> partition(string s) {
		vector<vector<string>> res;
		if (s.empty())
			return res;

		vector<string> temp;
		back_search(s, res, temp);
		return res;
	}

	void back_search(string s, vector<vector<string>>& res, vector<string>& temp)
	{
		//结束条件
		if (s.empty())
		{
			res.push_back(temp);
			return;
		}

		//all station
		for (int i = 1; i <= s.size(); i++)
		{
			string strs;
			if (s.size() == 1)
				strs = s;
			else
				strs = s.substr(0, i);
			if (check(strs))
			{
				temp.push_back(strs);
				back_search(s.substr(i), res, temp);
				temp.pop_back();
			}
		}
	}

	bool check(string& s)
	{
		if (s.size() == 1)
			return true;

		int left = 0;
		int right = s.size() - 1;
		while (left < right)
		{
			if (s[left++] != s[right--])
				return false;
		}

		return true;
	}
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值