Java implementation of LeetCode 761 special binary sequence (bracket problem)

761. Special binary sequence

A special binary sequence is a binary sequence with the following two properties:

The number of 0 is equal to the number of 1.
The number of 1s in each prefix of the binary sequence must be greater than or equal to 0.
Given a special binary sequence S, expressed as a string. Define an operation to first select two consecutive and non-empty special substrings of S, and then exchange them. (The two substrings are consecutive if and only if the last character of the first substring happens to be just before the first character of the second substring.)

After any number of operations, what is the largest result of the exchanged strings in lexicographic order?

Example 1:

Input: S = "11011000"
Output: "11100100"
Explanation: Exchange the
substring "10" (appears in S [1]) and "1100" (appears in S [3])
This is the largest result in lexicographical order after several operations.
Explanation:

The length of S does not exceed 50.
S is guaranteed to be a special binary sequence that satisfies the above definition.

PS:

既然是01子串,为什么不当成括号处理呢?

 

class Solution {
   public String makeLargestSpecial(String S) {
        StringBuilder sb = new StringBuilder();
        List<String> list = new ArrayList<>();
        int start = 0;
        int countOne = 0;
        for(int i = 0; i < S.length(); ++i) {
            countOne += S.charAt(i) == '1' ? 1 : -1;
            if(countOne == 0) {
                String str = S.substring(start + 1, i);
                list.add("1" + makeLargestSpecial(str) + "0");
                start = i + 1;
            }
        }
        Collections.sort(list);
        for(int i = list.size() - 1; i >= 0; --i) 
            sb.append(list.get(i));
        return sb.toString();
    }
}
Published 1,830 original articles · 30,000+ praises · 4.86 million views

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105555913