生成带有前缀 S 的 N 大小的二进制字符串,并且在字典上可能是最小的
给定一个二进制字符串S ,任务是根据以下条件从给定字符串S生成一个大小为N的二进制字符串(不要改变字符的位置):
- 字符串的前缀是 S。
- If 是字典上最小的可能。
- 1 和 0 的数量之间的绝对差是最小的。
例子:
Input: S = “101”, N = 8
Output: 10100011
Explanation: The prefix of output string is same as the string S.
The absolute difference between number of 0s and 1s is 0.
It is the lexicographically smallest possible which follows all the given condition.
Input: S = “001”, N = 7
Output: 0010011
方法:这个问题可以通过使用基于以下思想的贪心方法来解决:
In the case of a binary string, a string starting with ‘0’ is lexicographically smaller than the one starting with ‘1‘.
So, firstly make S the prefix and then find how many more 0s and 1s can be added. To make it lexicographically smallest, add all the 0s first and then the 1s.
按照下面提到的步骤来实施该方法。
- 计算 1 和 0 的数量并存储它们(分别在count1和count0中)。
- 找出(比如g ) count0和count1之间以及N和S长度之间的差异(比如在变量l中)。
- 计算我们需要在字符串长度中增加的大小以使字符串长度 = N并将其存储在l中。
- 现在添加尽可能多的0 s(将是(lg)/2 ),使得0的数量与N/2相同,然后为剩余的位置添加1 s。
下面是上述方法的实现:
Java
// Java program for above approach
import java.io.*;
import java.lang.*;
class GFG {
// Function to build string
String find_string(int n, String s)
{
// Declaring variable
int count0 = 0, count1 = 0;
// Check number of 1's and 0's
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
count0++;
}
else {
count1++;
}
}
String sb = s;
// Store difference in number of 1's
// and 0's
int g = count0 - count1;
// l store the value that how much 0's
// or 1's we need to add in string
int l = n - s.length();
l -= g;
// u store the count of
// number of 0's we need to insert
int u = l / 2;
while (u > 0) {
sb += '0';
u--;
}
if (l % 2 != 0) {
sb += '0';
}
while (sb.length() < n) {
sb += '1';
}
// Retutrn result
return sb;
}
// Driver code
public static void main(String[] args)
{
int N = 7;
String S = "001";
GFG g = new GFG();
// Function call
System.out.println(g.find_string(N, S));
}
}
0010011
时间复杂度: O(N)
辅助空间: O(1)