-
[LeetCode] 890. Find and Replace PatternLeetCode 2021. 10. 26. 11:26728x90
https://leetcode.com/problems/find-and-replace-pattern/
Find and Replace Pattern - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Find and Replace Pattern - Medium

String 벡터 words와, String pattern이 주어졌을때,
words 안의 단어들 중 pattern의 알파벳들을 다른 알파벳으로 치환하여 만들수 있는 것들을 골라내는 문제다.
하나는 words 알파벳을 pattern 알파벳으로,
다른 하나는 반대로 매핑해주는 맵을 각각 하나씩 만든다.
그 뒤, words를 훑으며 이미 나온 알파벳이면 각각의 맵을 검사하고,
아닐 경우엔 pattern에도 없을 경우 추가해주고, pattern에 있으면 잘못된 것이므로 바로 다음 word를 본다.
전체 풀이 코드
class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string> ret; unordered_map<char, char> w,p; for (string word:words) { int i; w.clear(); p.clear(); for (i=0; i<word.size(); i++) { if (w.find(word[i])==w.end()) { if (p.find(pattern[i])!=p.end()) break; w[word[i]] = pattern[i]; p[pattern[i]] = word[i]; } else if (p.find(pattern[i])==p.end() || w[word[i]]!=pattern[i] || p[pattern[i]]!=word[i]) break; } if (i==word.size()) ret.push_back(word); } return ret; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 75. Sort Colors (0) 2021.10.27 [LeetCode] 809. Expressive Words (0) 2021.10.26 [LeetCode] 226. Invert Binary Tree (0) 2021.10.26 [LeetCode] 1260. Shift 2D Grid (0) 2021.10.25 [LeetCode] 1417. Reformat The String (0) 2021.10.25