close
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?
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 most50
.S
is guaranteed to be a special binary string as defined above.
雖然我覺得我之後一定會忘記,不過還是記錄一下思路,
這題用的是recursion,然後找出special string(也就是1100這種1.0個數相同的string組合)將special string sort到最大
因為本身題目給的S 就會是一個 special string 所以可以這樣做
class Solution { public String makeLargestSpecial(String S) { int count = 0, i=0; List<String> res = new ArrayList(); for(int j=0; j < S.length(); j++){ if(S.charAt(j) == '0' ) count--; else count++; if(count == 0){ res.add("1"+makeLargestSpecial(S.substring(i+1,j))+"0"); i=j+1; } } Collections.sort(res, Collections.reverseOrder()); return String.join("", res); } }
全站熱搜
留言列表