题目:
力扣https://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;
}