Word Pattern

本文介绍了一个模式匹配问题的解决方法,通过使用C++实现了一种判断字符串是否遵循给定模式的算法。该算法通过比较模式中字符的对应关系与字符串中单词的对应关系来判断是否匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



题目描述
 Given a pattern and a string str, find if str follows the same pattern.


 Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.


 Examples:


 
  pattern = "abba", str = "dog cat cat dog" should return true.
 
 
  pattern = "abba", str = "dog cat cat fish" should return false.
 
 
  pattern = "aaaa", str = "dog cat cat dog" should return false.
 
 
  pattern = "abba", str = "dog dog dog dog" should return false.
 
输入
 第一行一个字符串


 第二行n和字符串(n表示第一行的字符串的长度)
输出true 或者 false样例输入
abba
dog cat cat dog
样例输出
true
提示
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题解:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
  char a[100];
  cin>>a;
  int len,t=0,z=0;
  len=strlen(a);
  z=((float)1/(float)2)*len*(len-1);
  string b[100];
  for(int i=0;i<len;i++)
  {
  	cin>>b[i];
  } 
  for(int i=0;i<len;i++)
  {
  	for(int j=i+1;j<len;j++)
  	{
  		if((a[i]==a[j]&&b[i]==b[j])||(a[i]!=a[j]&&b[i]!=b[j]))
  	     t++;
  	}
  }
  if(t==z)
  cout<<"true";
  else
  cout<<"flase";
  return 0;
}

PS:我觉得这个方法好像哪里有问题。还希望各位朋友能不吝赐教!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值