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进阶路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【大前端攻城狮之路】用 Typewrit
- 下一篇: AI Agent现实应用与未来展望:从个