【LeetCode】761 Special Binary String

【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?

Note:
- S has length at most 50.
- S is guaranteed to be a special binary string as defined above.

题目分析:
  1. 特殊二进制串中1和0的数目相等
  2. 在二进制串中的任意一个前缀中,1的数量肯定大于等于0的数量

 第2点可以说是解题的关键,在满足第一个条件的情况下,该二进制串第一位肯定是1,最后一位肯定是0。否则就不满足第二点要求;比如说有字符串"0101",该字符串满足第一点要求,但是并不满足第二点要求;

原题链接

代码

/*
     * 1、找到满足要求的特殊二进制串,该二进制串肯定是以1开始,以0结束,
     * 所以除去最前面的1和最后面的0,中间部分也是特殊二进制串,继续对中间部分进行递归处理。
     * 2、将找到的满足要求的特殊二进制串放入list中,然后按照字典序进行排序。
     * 3、返回进行字典序排序的结果
     * @param S
     * @return
     */
public String makeLargestSpecial(String S) {
        //如果count==0,说明到当前位置为止,0和1的数量相同
        int count = 0;
        int i = 0;
        //用来存储当前特殊二进制字符串
        List<String> list = new ArrayList<String>();

        for(int j = 0; j < S.length(); j++) {
            if(S.charAt(j) == '1')
                count++;
            else
                count--;
            if(count == 0) {//找到了符合要求的特殊二进制字符串
                //体现了第二点要求
                list.add("1" + makeLargestSpecial(S.substring(i+1,j)) + "0");
                i = j + 1;
            }
        }
        //对当前找到的特殊二进制字符串进行字典序排序
        Collections.sort(list,Collections.reverseOrder());

        return String.join("",list);
    }
参考资源链接:[C语言实现LeetCode第87题字符串错乱问题详解](https://wenku.youkuaiyun.com/doc/3gininbodv?utm_source=wenku_answer2doc_content) 为了帮助你理解并实现LeetCode上的Scramble String问题,我强烈推荐查看这份资源:《C语言实现LeetCode第87题字符串错乱问题详解》。这份资料将为你提供详尽的算法解析和C语言代码实现,直接针对你当前面临的挑战。 Scramble String问题可以通过递归和动态规划的方法来解决。以下是一个高效实现的步骤概述和源代码示例: (步骤、代码、mermaid流程图、扩展内容,此处略) 在这个示例中,我们首先检查两个字符串的长度是否相等,然后进行递归调用来比较每个字符的所有可能划分点。如果找到一个划分点,使得s1的一个子串能够错乱成s2的一个子串,且s1剩余部分也能错乱成s2剩余部分,那么我们就找到了一个有效的解。 通过这种方法,我们能够有效地判断一个字符串是否可以通过错乱得到另一个字符串。对于希望进一步提升算法设计和编程能力的读者,我建议深入阅读这份题解资源:《C语言实现LeetCode第87题字符串错乱问题详解》。这份资源不仅解答了你当前的问题,还提供了更多细节和深度内容,帮助你在C语言编程和算法实现方面更上一层楼。 参考资源链接:[C语言实现LeetCode第87题字符串错乱问题详解](https://wenku.youkuaiyun.com/doc/3gininbodv?utm_source=wenku_answer2doc_content)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值