890. Find and Replace Pattern的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/82627208

使用map容器即可,但是要注意的是这个关系正反都是一一对应的,两个值都应该是key,就是ABB不能对应ccc这样的字符串。但是map只有第一个值是key,我的解决方法是存储两遍,分别作为key,检查的时候也检查两遍即可。速度打败100

class Solution {
public:
	vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
		vector<string> result;
		for (int i = 0; i < words.size(); i++)
		{
			int l = words[i].length();
			int flag = 1;
			map<char, char> check1;
			map<char, char> check2;
			for (int j = 0; j < l; j++)
			{
				if (!check1.count(pattern[j]))
				{
					check1.insert(make_pair(pattern[j], words[i][j]));
					check2.insert(make_pair(words[i][j], pattern[j]));
				}
				else if ((check1[pattern[j]] != words[i][j]) || (check2[words[i][j]] != pattern[j]))
					  { flag = 0; break; }
			}
			if (flag == 1) result.push_back(words[i]);
		}
		return result;
	}
};

还有一种思路是对于按照字母出现的顺序和次数形成一种编号,然后比较pattern的编号和words的编号是否一样。

class Solution {
private:
    vector<int> normalize(const string& str) {
        if (str.empty()) return {};
        int mapped = 0;
        int mapping [26] {0};
        for (char ch : str) {
            if (mapping[ch-'a'] == 0) mapping[ch-'a'] = mapped++; 
        }
        vector<int> fingerprint(str.size());
        for (int i = 0; i < str.size(); ++i) {
            fingerprint[i] = mapping[str[i]-'a'];
        }
        return fingerprint;
    }
public:
    vector<string> findAndReplacePattern(const vector<string>& words, const string& pattern) {
        vector<string> matches;
        const auto pattern_fingerprint = normalize(pattern);
        for (const auto& word : words) {
            if (normalize(word) == pattern_fingerprint) matches.push_back(word);
        }
        return matches;
    }
};

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/82627208