LeetCode-in-Java

2767. Partition String Into Minimum Beautiful Substrings

Medium

Given a binary string s, partition the string into one or more substrings such that each substring is beautiful.

A string is beautiful if:

Return the minimum number of substrings in such partition. If it is impossible to partition the string s into beautiful substrings, return -1.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = “1011”

Output: 2

Explanation: We can paritition the given string into [“101”, “1”].

It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into.

Example 2:

Input: s = “111”

Output: 3

Explanation: We can paritition the given string into [“1”, “1”, “1”].

It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into.

Example 3:

Input: s = “0”

Output: -1

Explanation: We can not partition the given string into beautiful substrings.

Constraints:

Solution

public class Solution {
    private boolean ispower(int num) {
        int pow = 1;
        while (pow < num) {
            pow = pow * 5;
        }
        return pow == num;
    }

    private int backtrack(int ind, String s) {
        if (ind >= s.length()) {
            return 0;
        }
        if (s.charAt(ind) == '0') {
            return 999;
        }
        int temp = 999;
        int runCount = 0;
        for (int i = ind; i < s.length(); i++) {
            runCount = runCount * 2;
            if (s.charAt(i) == '1') {
                runCount++;
            }
            if (this.ispower(runCount)) {
                temp = Math.min(temp, 1 + this.backtrack(i + 1, s));
            }
        }
        return temp;
    }

    public int minimumBeautifulSubstrings(String s) {
        int res = this.backtrack(0, s);
        if (res < 999) {
            return res;
        }
        return -1;
    }
}