给定一个二进制字符串S ,任务是找到可以分割的最大部分数,以使每个部分都可以被2整除。如果字符串不能满足给定条件进行拆分,则输出-1 。
例子:
Input: S = “100”
Output: 2
The splits are as follows:
“10” ans “0”.
Input: S = “110”
Output: 1
方法:这个问题可以贪婪地得到解决,从左边月底开始,把一个切口在索引j,使得j是针对哪个子串高达j通过2整除的最小的指数。现在,使用剩下的字符串其余部分继续此步骤。众所周知,任何以0结尾的二进制数都可以被2整除。因此,在每个零后都加一个小数,答案将等于字符串中零的数目。唯一不可能的答案是当给定的字符串为奇数时,即无论如何对字符串进行切割,最后分割的部分将始终为奇数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the required count
int cntSplits(string s)
{
// If the splitting is not possible
if (s[s.size() - 1] == '1')
return -1;
// To store the final ans
int ans = 0;
// Counting the number of zeros
for (int i = 0; i < s.size(); i++)
ans += (s[i] == '0');
// Return the final answer
return ans;
}
// Driver code
int main()
{
string s = "10010";
cout << cntSplits(s);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the required count
static int cntSplits(String s)
{
// If the splitting is not possible
if (s.charAt(s.length() - 1) == '1')
return -1;
// To store the final ans
int ans = 0;
// Counting the number of zeros
for (int i = 0; i < s.length(); i++)
ans += (s.charAt(i) == '0') ? 1 : 0;
// Return the final answer
return ans;
}
// Driver code
public static void main(String []args)
{
String s = "10010";
System.out.println(cntSplits(s));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the required count
def cntSplits(s) :
# If the splitting is not possible
if (s[len(s) - 1] == '1') :
return -1;
# To store the count of zeroes
ans = 0;
# Counting the number of zeroes
for i in range(len(s)) :
ans += (s[i] == '0');
# Return the final answer
return ans ;
# Driver code
if __name__ == "__main__" :
s = "10010";
print(cntSplits(s));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the required count
static int cntSplits(String s)
{
// If the splitting is not possible
if (s[s.Length - 1] == '1')
return -1;
// To store the final ans
int ans = 0;
// Counting the number of zeros
for (int i = 0; i < s.Length; i++)
ans += (s[i] == '0') ? 1 : 0;
// Return the final answer
return ans;
}
// Driver code
public static void Main(String []args)
{
String s = "10010";
Console.WriteLine(cntSplits(s));
}
}
// This code is contributed by Rajput-Ji
输出:
3
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。