日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Special Binary String——LeetCode进阶路

發布時間:2025/5/22 编程问答 28 如意码农
生活随笔 收集整理的這篇文章主要介紹了 Special Binary String——LeetCode进阶路 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原題鏈接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);
}
}

總結

以上是生活随笔為你收集整理的Special Binary String——LeetCode进阶路的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。