String 的最小分区,使得每个部分最多为 K
给定一个大小为N的字符串S ,由数字1-9和一个正整数K组成,任务是最小化字符串的分区,使得每个部分都是 st most K 。如果无法对字符串进行分区打印 -1。
例子:
Input: S = “3456”, K = 45
Output: 2
Explanation: One possible way is to partition as 3, 45, 6.
Another possibility is 3, 4, 5, 6, which uses 3 partition.
No configuration needs less than 2 partitions. Hence, the answer is 2.
Input: S = “7891634”, K = 21
Output: 5
Explanation: The minimum number of partitions is
7, 8, 9, 16, 3, 4, which uses 5 partitions.
Input: S = “67142849”, K = 39
Output: 5
方法:解决此问题的方法基于以下思想:
Make each partition have a value as large as possible with an upper limit of K.
An edge case is if it’s impossible to partition the string. It will happen if the maximum digit in the string is larger than K..
请按照以下步骤解决此问题:
- 从i = 0 到 N-1迭代字符串的字符:
- 如果到目前为止形成的数字最多为 K,则继续进行此分区。否则,增加分区数。
- 否则,如果当前数字大于K ,则返回-1 。
- 迭代字符串后可能没有考虑最后一个数字,因此检查最后一个分区是否大于 0。如果是,则增加分区数(比如ans ) 由1 。
- 最后,返回ans – 1 ,因为我们需要找到最小的分区数,它比形成的数字少一。
下面是上述方法的实现:
C++
// C++ program for above implementation
#include
using namespace std;
// Function to count the minimum number
// of partitions
int minimumCommas(string& s, int k)
{
// Length of the string 's'.
int n = s.size();
// Store the current number formed.
long long cur = 0;
// 'ans' stores the final answer.
int ans = 0;
// Iterate over the string.
for (int i = 0; i < n; ++i) {
// If we can include this digit in the
// current number
if (cur * 10 + (s[i] - '0') <= k) {
// Include this digit in
// the current number.
cur = cur * 10 + (s[i] - '0');
}
else {
// If 'cur' is '0',
// it's impossible to partition
if (cur == 0) {
// Return the integer '-1'
return -1;
}
else {
// Increment the answer 'ans'
ans++;
// Set cur to the current digit
cur = s[i] - '0';
}
}
}
// If cur > 0, means the last number is cur
if (cur > 0) {
// Increment the 'ans'
ans++;
}
// Return the number of partitions
return ans - 1;
}
// Driver code
int main()
{
// Input
string S = "7891634";
int K = 21;
// Function call
cout << minimumCommas(S, K);
return 0;
}
5
时间复杂度: O(N)
辅助空间: O(1)