力扣-每日一题(890)查找和替换模式

题目:

力扣icon-default.png?t=M4ADhttps://leetcode.cn/problems/find-and-replace-pattern/大致题意:匹配模式字符串,需要格式一致

重复替换的出现的情况:abbcdd匹配xyyzyy 这种情况会出现重复替换 题目要求替换只能一对一,即y要么换成b要么换成d,不能同时换成两个

我的解题思路:通过两个数组记录从头开始的匹配情况,如果出现两者其中一个发生过替换且替换对象不是两者的另一个,那么匹配失败,进行下一个匹配

#include<iostream>
#include<map>
#include<string>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;

class Solution {
public:
	vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
		int a[26] = { 0 };//记录pattern字符串的情况
		int b[26] = { 0 };//记录需要匹配的字符串情况
		vector<string>x;
		for (int i = 0; i < words.size(); i++)
		{
			if (pattern.size() != words[i].size())
			{
				continue;//字符串长度不一样,无法匹配,直接跳过
			}
			else
			{
				fill(a, a + 26, 0);//重置数组
				fill(b, b + 26, 0);
				int p = 1;//记录匹配的编号
				int f = 1;//判断是否匹配
				for (int j = 0; j < pattern.size(); j++)
				{
					int x = pattern[j] - 'a';//将字母换成对应的0~25数组的下标
					int y = words[i][j] - 'a';
					if (a[x] == b[y])//两者的匹配编号相同
					{
						if (a[x] == 0)//匹配编号为0,都未进行编号,进行赋值新的匹配编号
						{
							a[x] = p;
							b[y] = p;
							p++;//赋值完,加1获得新的匹配编号
						}
					}
					else //匹配失败
					{
						f = 0;
						break;
					}
				}
				if (f)
				{
					x.push_back(words[i]);
				}
			}
		}
		return x;
	}
};

int main()
{
	vector<string>x = { "abc", "deq", "mee", "aqq", "dkd", "ccc" };
	string y = "abb";
	Solution sc;
	vector<string>out;
	out = sc.findAndReplacePattern(x, y);
	for (int i = 0; i < out.size(); i++)
	{
		cout << out[i] << endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值