Special Binary String——LeetCode进阶路

65 篇文章 1 订阅

原题链接https://leetcode.com/problems/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.
字符0的个数与字符1的个数相等
Every prefix of the binary string has at least as many 1’s as 0’s.
二进制序列的每一个前缀码中 1 的数量要大于等于 0 的数量
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:

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

思路分析

给定二进制子串,在满足“特殊串”的两个要求得情况下,可以对子串进行任意次数的交换,返回字典序中最大的字符串。
第一直觉就是递归啦,对了一定要提看的大神的理解,爆炸赞,把问题看做括号字符串ヾ(゚∀゚ゞ)
1视为左括号,0视为右括号,特殊串的要求就变成括号必须能够配对,且在任意时刻左括号都要大于等于右括号~
eg : 11011000 ——> (() (()))
11100100 ——> ( (()) () )
要求是字典序最大,也就是1要尽量在前面,即左括号们尽量在前边
其实从样例也很直观,想让左括号们在前边,就需要在前边放那些嵌套层数多的。
注意:开头和结尾的那对括号是必须的,不可以改变,所以只要调整其内的子串即可。
嵌套问题当然找递归啦,最后排序得出结果,(o゜▽゜)o☆[BINGO!]

AC解

下面贴的是借鉴了大神后的优化版,我与大神的差距还隔着N个高级特性哇!

class Solution {
    public String makeLargestSpecial(String S) {
        if(S == null)
        {
            return null;
        }
        
        int count = 0;
        List<String> res = new LinkedList<>();
        for(int i=0,j=0; i<S.length() ; i++)
        {
            count = (S.charAt(i)=='1') ? count+1 : count-1;
            if(count == 0)
            {
                res.add('1'+ makeLargestSpecial(S.substring(j+1,i)) +'0');
                j = i + 1;
            }
        }
        
        Collections.sort(res,Collections.reverseOrder());
        return String.join("",res);
    }
}

在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值