LeetCode #761 - Special Binary String

题目描述:

Special binary strings are binary strings with the following two properties:

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.

Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)

At the end of any number of moves, what is the lexicographically largest resulting string possible?

Example 1:

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 after some number of swaps.

Note:

1. S has length at most 50.

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

特殊的二进制字符串的定义是0和1个数相同,而且任意前缀中1的个数大于等于0。所以特殊二进制字符串就是合法的括号匹配,求问如果可以交换任意两个相邻的特殊二进制子字符串,能够得到的最大字典序的字符串是什么。既然能任意交换两个相邻的子字符串,就相当于求出所有的特殊二进制子字符串,调用递归求出每个子字符串的最大字典序排列,然后再将所有的子字符串排序。

class Solution {
public:
    string makeLargestSpecial(string S) {
        int count=0;
        int i=0; //特殊二进制子字符串的起点
        int j=0; //特殊二进制子字符串的终点
        vector<string> v;
        while(j<S.size())
        {
            if(S[j]=='1') count++;
            else count--;
            if(count==0) //找到了一个特殊二进制子字符串
            {   //特殊二进制子字符串首尾必定为1和0,所以可以调用递归求中间的子字符串的最大排列
                v.push_back("1"+makeLargestSpecial(S.substr(i+1,j-i-1))+"0");
                j++;
                i=j;
            }
            else j++;
        }
        sort(v.begin(),v.end()); //排序之后较小的字符串在前面
        string result;
        for(int k=v.size()-1;k>=0;k--) result+=v[k];
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值