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

vector<vector<string>> partition(string s)
	{
		/*
		在s的len个字符之间放len-1个木板,并且在两端个放一个,这样就有len+1个木板
		*/
		int len=s.length();
		int BIG=2*len;
		int num_line=len+1;
		//表明两个木板之间substr是否为回文,如果有则代表它两端的木板可以直接相连,
		//否则,代表它两端的木板必须通过其他木板相连,也就是不相连
		//将这些木板作为节点,上面的连接关系作为边,建立图
		vector<int> isPalindrome(num_line*num_line);
		/*
		if s[i]==s[j]
			f(i,j)=f(i+1,j-1)
		else
			f(i,j)=0
		*/
		for(int l=1;l<=len;l++)//两个木板之间有多少个字符
		{
			for (int i=0;i+l<num_line;i++)//从第0个木板开始,i+l为木板的序号
			{
				if (l==1)
				{
					isPalindrome[i*num_line+(i+l)]=1;
				}
				else if(l==2)
				{
					if (s[i]==s[i+l-1])
						isPalindrome[i*num_line+(i+l)]=1;
					else
						isPalindrome[i*num_line+(i+l)]=BIG;
				}
				else
				{
					if (s[i]==s[i+l-1])
						isPalindrome[i*num_line+(i+l)]=isPalindrome[(i+1)*num_line+(i+l-1)];
					else
						isPalindrome[i*num_line+(i+l)]=BIG;
				}
			}
		}

		vector<vector<int>> index;
		vector<int> start;
		start.push_back(0);
		index.push_back(start);
		for (int i=0;i<num_line;i++)
		{
			int max_len=index.size();
			vector<vector<int>>::iterator iter=index.begin();
			for(int j=0;j<max_len;j++)
			{
				vector<int> current_line=index[j];
				if (current_line.back()>=num_line-1) continue;
				bool first_time=true;
				for(int a=current_line.back()+1;a<num_line;a++)
				{
					if(isPalindrome[current_line.back()*num_line+a]==1)
					{
						if (first_time)	
						{
							index[j].push_back(a);
							first_time=false;
						}
						else
						{
							vector<int> tmp=current_line;
							tmp.push_back(a);
							index.insert(index.begin()+j,tmp);
							j++;
							max_len++;
						}
					}
				}
			}
		}

		vector<vector<string>> res;
		for(int i=0;i<index.size();i++)
		{
			vector<string> tmp;
			res.push_back(tmp);
			for(int j=0;j<index[i].size()-1;j++)
			{
				res[i].push_back(s.substr(index[i][j],index[i][j+1]-index[i][j]));
			}
		}
		return res;
	}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值