890. Find and Replace Pattern
MediumView on LeetCode
Time: O(n · m)
Space: O(n · m)
Problem Overview
Find and Replace Pattern (Medium) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Check isomorphism via bidirectional character mapping; both word→pattern and pattern→word mappings must be consistent.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Check isomorphism via bidirectional character mapping; both word→pattern and pattern→word mappings must be consistent.
Related patterns: Array, Hash Table, String
890.cs
C#
// Approach: Check isomorphism via bidirectional character mapping; both word→pattern and pattern→word mappings must be consistent.
// Time: O(n · m) Space: O(n · m)
public class Solution
{
public IList<string> FindAndReplacePattern(string[] words, string pattern)
{
IList<string> ans = new List<string>();
foreach (string word in words)
{
if (IsIsomorphic(word, pattern))
ans.Add(word);
}
return ans;
}
private bool IsIsomorphic(string w, string p)
{
int[] wordMap = new int[128];
int[] patternMap = new int[128];
for (int i = 0; i < w.Length; i++)
{
if (wordMap[w[i]] != patternMap[p[i]])
return false;
wordMap[w[i]] = i + 1;
patternMap[p[i]] = i + 1;
}
return true;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)