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的個(gè)數(shù)與字符1的個(gè)數(shù)相等
Every prefix of the binary string has at least as many 1’s as 0’s.
二進(jìn)制序列的每一個(gè)前綴碼中 1 的數(shù)量要大于等于 0 的數(shù)量
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.
思路分析
給定二進(jìn)制子串,在滿足“特殊串”的兩個(gè)要求得情況下,可以對(duì)子串進(jìn)行任意次數(shù)的交換,返回字典序中最大的字符串。
第一直覺就是遞歸啦,對(duì)了一定要提看的大神的理解,爆炸贊,把問題看做括號(hào)字符串ヾ(???ゞ)
1視為左括號(hào),0視為右括號(hào),特殊串的要求就變成括號(hào)必須能夠配對(duì),且在任意時(shí)刻左括號(hào)都要大于等于右括號(hào)~
eg : 11011000 ——> (() (()))
11100100 ——> ( (()) () )
要求是字典序最大,也就是1要盡量在前面,即左括號(hào)們盡量在前邊
其實(shí)從樣例也很直觀,想讓左括號(hào)們?cè)谇斑叄托枰谇斑叿拍切┣短讓訑?shù)多的。
注意:開頭和結(jié)尾的那對(duì)括號(hào)是必須的,不可以改變,所以只要調(diào)整其內(nèi)的子串即可。
嵌套問題當(dāng)然找遞歸啦,最后排序得出結(jié)果,(o゜▽゜)o☆[BINGO!]
AC解
下面貼的是借鑒了大神后的優(yōu)化版,我與大神的差距還隔著N個(gè)高級(jí)特性哇!
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);
}
}
總結(jié)
以上是生活随笔為你收集整理的Special Binary String——LeetCode进阶路的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【大前端攻城狮之路】用 Typewrit
- 下一篇: AI Agent现实应用与未来展望:从个