Binary String Matching

本博客介绍了一个算法,用于计算一个字符串作为另一个字符串中子串出现的次数,适用于只包含二进制字符的场景。
描述
Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
输入
The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
输出
For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.
样例输入
3
11
1001110110
101
110010010010001
1010
110100010101011 
样例输出
3
0
3 
#include<stdio.h>
#include<string.h>
int main()
{
	int n,t;
	char a[10],b[1000],*p;
	scanf("%d",&n);
	while(n--)
	{
		t=0;
		scanf("%s%s",a,b);
		p=b;
		while( (p=strstr(p,a)) !=NULL )
		{
			t++;
			p++;
		}
		printf("%d\n",t);
	}
	return 0;
}
//其它人写的,差不多
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main()
{
	int n;
	 char A[11];
	 char B[1100];
	 char *p;
	cin>>n;
	while(n--)
	{
		int count=0;
      cin>>A>>B;
      p=strstr(B,A);
	  while(p)
	  {
		  count++;
		  p=p+1;
		  p=strstr(p,A);
	  }
	  cout<<count<<endl;
	}
	return 0;
}


SHA-256 是一种加密哈希函数,生成长度为 256 位的哈希值。通常情况下,SHA-256 的输出以十六进制字符串的形式表示,而不是纯二进制格式[^1]。为了确保输出不是纯二进制,并且其中包含至少 20 个不连续的 `0`,可以通过以下方式修改代码。 ### 修改 Python 代码输出 SHA-256 值 默认情况下,Python 的 `hashlib.sha256()` 返回的是二进制数据,通过 `.hexdigest()` 可以将其转换为十六进制字符串形式。若希望满足特定条件(如包含至少 20 个不连续的 `0`),则可以对原始哈希结果进行处理后再输出。 以下是一个示例代码: ```python import hashlib def generate_sha256_with_zeros(input_string): # 计算原始 SHA-256 哈希值 hash_obj = hashlib.sha256(input_string.encode('utf-8')) hex_digest = hash_obj.hexdigest() # 插入额外字符以确保包含至少 20 个不连续的 '0' result = '' zero_count = 0 for ch in hex_digest: result += ch if ch != '0' and zero_count < 20: result += '0' zero_count += 1 return result[:64] # 确保最终长度仍为 64 个字符 # 示例使用 input_str = "example string" output_hash = generate_sha256_with_zeros(input_str) print("Modified SHA-256 Hash:", output_hash) ``` 此代码在原始 SHA-256 哈希值的基础上插入了额外的 `'0'` 字符,以确保输出中包含至少 20 个不连续的 `'0'`。最终输出仍然是十六进制字符串格式,而非纯二进制形式。 ### 输出格式说明 - **原始输出**:`hashlib.sha256().hexdigest()` 返回的是一个 64 位的十六进制字符串。 - **修改后的输出**:在保留原始结构的前提下,插入了多个 `'0'`,使得输出中至少包含 20 个不连续的 `'0'`。 - **避免二进制输出**:使用 `.hexdigest()` 而非 `.digest()`,确保输出始终是文本格式,而非字节流[^3]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值