给定两个特殊字符,第一个字符可以用0表示,第二个字符可以用10或11表示。现在给出一个由几个位表示的字符串。任务是返回它代表的字符数。请注意,给定的字符串始终有效。
例子:
Input: str = “11100”
Output: 3
“11”, “10” and “0” are the required characters.
Input: str = “100”
Output: 2
方法:解决问题的方法是,如果当前字符为0,则表示单个字符为1位,但是如果当前字符为1,则其后的下一位必须包含在由两位组成的字符,如下所示:没有以1开头的单个位字符。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of required characters
int countChars(string str, int n)
{
int i = 0, cnt = 0;
// While there are characters left
while (i < n) {
// Single bit character
if (str[i] == '0')
i++;
// Two-bit character
else
i += 2;
// Update the count
cnt++;
}
return cnt;
}
// Driver code
int main()
{
string str = "11010";
int n = str.length();
cout << countChars(str, n);
return 0;
}
Java
// Java implementation of the above approach
class GFG {
// Function to return the count
// of required characters
static int countChars(String str, int n)
{
int i = 0, cnt = 0;
// While there are characters left
while (i < n) {
// Single bit character
if (str.charAt(i) == '0')
i += 1;
// Two-bit character
else
i += 2;
// Update the count
cnt += 1;
}
return cnt;
}
// Driver code
public static void main (String[] args)
{
String str = "11010";
int n = str.length();
System.out.println(countChars(str, n));
}
// This code is contributed by AnkitRai01
}
Python3
# Python3 implementation of the approach
# Function to return the count
# of required characters
def countChars(string, n) :
i = 0; cnt = 0;
# While there are characters left
while (i < n) :
# Single bit character
if (string[i] == '0'):
i += 1;
# Two-bit character
else :
i += 2;
# Update the count
cnt += 1;
return cnt;
# Driver code
if __name__ == "__main__" :
string = "11010";
n = len(string);
print(countChars(string, n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the count
// of required characters
static int countChars(string str, int n)
{
int i = 0, cnt = 0;
// While there are characters left
while (i < n)
{
// Single bit character
if (str[i] == '0')
i += 1;
// Two-bit character
else
i += 2;
// Update the count
cnt += 1;
}
return cnt;
}
// Driver code
public static void Main ()
{
string str = "11010";
int n = str.Length;
Console.WriteLine(countChars(str, n));
}
}
// This code is contributed by AnkitRai01
输出:
3
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。