761. Special Binary String

Difficulty:
Related Topics:
Similar Questions:

Problem

Special binary strings are binary strings with the following two properties:

You are given a special binary 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.

Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.

  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.

Example 2:

Input: s = "10"
Output: "10"

  Constraints:

Solution (Java)

import java.util.PriorityQueue;

public class Solution {
    public String makeLargestSpecial(String s) {
        if (s == null || s.length() == 0 || s.length() == 2) {
            return s;
        }
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> b.compareTo(a));
        int acc = 1;
        int prev = 0;
        for (int i = 1; i <= s.length(); i++) {
            if (acc == 0) {
                if (!(prev == 0 && i == s.length())) {
                    pq.add(makeLargestSpecial(s.substring(prev, i)));
                }
                prev = i;
            }
            if (i == s.length()) {
                break;
            }
            if (s.charAt(i) == '1') {
                acc++;
            } else {
                acc--;
            }
        }
        StringBuilder ans = new StringBuilder();
        while (!pq.isEmpty()) {
            ans.append(pq.poll());
        }
        if (ans.length() == 0) {
            ans.append('1');
            ans.append(makeLargestSpecial(s.substring(1, s.length() - 1)));
            ans.append('0');
        }
        return ans.toString();
    }
}

Solution (C++)

class Solution {
 public:
  string makeLargestSpecial(string S) {
    vector<string> specials;
    int count = 0;

    for (int i = 0, j = 0; j < S.length(); ++j) {
      count += S[j] == '1' ? 1 : -1;
      if (count == 0) {  // find a special string
        const string& inner = S.substr(i + 1, j - i - 1);
        specials.push_back('1' + makeLargestSpecial(inner) + '0');
        i = j + 1;
      }
    }

    sort(begin(specials), end(specials), greater<>());
    return join(specials);
  }

 private:
  string join(const vector<string>& specials) {
    string joined;
    for (const string& special : specials)
      joined += special;
    return joined;
  }
};

Explain:

nope.

Complexity: