Formatted question description: https://leetcode.ca/all/761.html

761. Special Binary String

Level

Hard

Description

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:

  1. S has length at most 50.
  2. S is guaranteed to be a special binary string as defined above.

Solution

Use recursion. For each non-empty special substring, swap inside itself to form the lexicographically largest special substring, and then sort the special substrings to form the lexicographically largest special substring.

Obviously, each special substring must start with 1 and end with 0. Each time a smaller special substring is obtained, insert 1 at the start and insert 0 at the end to form a larger special substring.

class Solution {
    public String makeLargestSpecial(String S) {
        List<String> list = new ArrayList<String>();
        int start = 0;
        int ones = 0;
        int length = S.length();
        for (int i = 0; i < length; i++) {
            char c = S.charAt(i);
            if (c == '1')
                ones++;
            else
                ones--;
            if (ones == 0) {
                String substr = S.substring(start + 1, i);
                String curSpecial = "1" + makeLargestSpecial(substr) + "0";
                list.add(curSpecial);
                start = i + 1;
            }
        }
        Collections.sort(list);
        StringBuffer sb = new StringBuffer();
        for (int i = list.size() - 1; i >= 0; i--)
            sb.append(list.get(i));
        return sb.toString();
    }
}

All Problems

All Solutions