检查编码是否代表唯一的二进制字符串
给定长度为 k 的二进制字符串的编码,任务是找出给定的编码是否唯一标识二进制字符串。编码具有连续 1 的计数(由 0 分隔)。
例如,11111 的编码是 {5},01101010 的编码是 {2,1,1},111011 的编码是 {3,2}。
例子 :
Input: encoding[] = {3, 3, 3}
Length, k = 12
Output: No
Explanation: There are more than one possible
binary strings. The strings are 111011101110
and 011101110111. Hence “No”
Input: encoding[] = {3, 3, 2}
Length, k = 10
Output: Yes
Explanation: There is only one possible encoding
that is 1110111011
一种天真的方法是取一个空字符串并遍历 n 个整数到 encoding[0] 中给出的没有 1,然后向其添加 1 个零,然后 encoding[1] 1,最后检查字符串长度是否等于 k 然后打印“是”或打印“否”
一种有效的方法是将所有 n 个整数相加,然后将 (n-1) 添加到 sum 并检查它是否等于 K,因为 n-1 将是每个 1 之间的零的数量。检查 sum 是否等于 k,以获得恰好一个字符串,否则有更多或没有。
C++
// C++ program to check if given encoding
// represents a single string.
#include
using namespace std;
bool isUnique(int a[], int n, int k)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
sum += n - 1;
// Return true if sum becomes k
return (sum == k);
}
// Driver Code
int main()
{
int a[] = {3, 3, 3};
int n = sizeof(a) / sizeof(a[0]);
int k = 12;
if (isUnique(a, n, k))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to check if given encoding
// represents a single string.
import java.io.*;
class GFG
{
static boolean isUnique(int []a, int n, int k)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
sum += n - 1;
// Return true if sum becomes k
return (sum == k);
}
// Driver Code
static public void main (String[] args)
{
int []a = {3, 3, 3};
int n = a.length;
int k = 12;
if (isUnique(a, n, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by vt_m
Python3
# Python 3 program to check if given
# encoding represents a single string.
def isUnique(a, n, k):
sum = 0
for i in range(0, n, 1):
sum += a[i]
sum += n - 1
# Return true if sum becomes k
return (sum == k)
# Driver Code
if __name__ == '__main__':
a = [3, 3, 3]
n = len(a)
k = 12
if (isUnique(a, n, k)):
print("Yes")
else:
print("No")
# This code is contributed by
# Surndra_Gangwar
C#
// C# program to check if given encoding
// represents a single string.
using System;
class GFG
{
static bool isUnique(int []a, int n, int k)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
sum += n - 1;
// Return true if sum becomes k
return (sum == k);
}
// Driver Code
static public void Main ()
{
int []a = {3, 3, 3};
int n = a.Length;
int k = 12;
if (isUnique(a, n, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m
PHP
Javascript
输出 :
No