LeetCode | 761. Special Binary String 最优子结构难题

Special binary strings are binary strings with the following twoproperties:

· The number of 0's is equal to the number of 1's.

· Every prefix of the binary string has at least as many 1's as 0's.

Givena special string S, a move consistsof choosing two consecutive, non-empty, special substrings of S, and swapping them.(Two stringsare consecutive if the last character of the first string is exactly one indexbefore the first character of the second string.)

Atthe end of any number of moves, what is the lexicographically largest resultingstring possible?

Example1:

Input: S = "11011000"

Output: "11100100"

Explanation:

The strings "10" [occuring at S[1]] and"1100" [at S[3]] are swapped.


This is the lexicographically largest string possible aftersome number of swaps.

Note:

1.      S has length at most 50.

2.      S is guaranteed to be a special binarystring as defined above.

这一题怎么说呢,给你一个0,1的字符串,让你按照他的规则将子串交换,然后问你怎样才能得到在字典序中最大的一个字符串,老实说,这一题我刚开始看的时候是一点思路都没有的,看了别人的解决方法才想到怎么解的


这一题的关键是把每一个字符串想象成一座山峰,然后每次交换可以看成是把这座山峰的两个海平面相同的子峰交换,当然,每座子峰也有自己的子峰,经过多次交换子峰之后,使得这座山峰上坡尽可能在下坡之前

很明显,这一题是一道最优子结构的题目,可以证明,除了最开始给的山峰以外,任何一座子峰的子峰的海拔都高于这座子峰的海拔,因此先要给给定的字符串首尾加上1和0,使最开始给的山峰的所有子峰的海平面都低于最开始给的山峰的海平面

要想最开始给的山峰取得最优解,使得其每一个子峰都取得最优解,然后对子峰进行排序即可,

class Solution {
public:
static bool cmp(string a, string b)
{
	return a.compare(b) > 0;
}
string p(string S)
{
	int n = S.size();
	if (n == 2) return S;
	vector<string> strSort;
	int temp = 0; int l = 1;
	for (int index = 1; index < n - 1; index++)
	{
		if (S[index] == '1') temp += 1;
		else temp -= 1;
		if (temp == 0)
		{
		    strSort.push_back(p(S.substr(l, index - l + 1)));
			l = index + 1;
	      }
	}
	sort(strSort.begin(), strSort.end(),cmp);
	string tmp = "";
	for (int i = 0; i < strSort.size(); i++)
		tmp.append(strSort[i]);
	return "1" + tmp + "0";
	  
}
string makeLargestSpecial(string S) {
	S = "1" + S + "0";
	string result = p(S);
	return result.substr(1, result.size() - 2);
}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值