I solved this problem from LeetCode:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
I was able to solve this problem by using a Dictionary
to keep track of the relation between the pattern
and the str
:
public class Solution {
public bool WordPattern(string pattern, string str)
{
var result = str.Split(' ').ToList();
var mapPattern = new Dictionary<char, string>();
if (result.Count != pattern.Count())
{
return false;
}
string matchstr;
int index = 0;
foreach (var c in pattern)
{
if (mapPattern.TryGetValue(pattern[index], out matchstr))
{
if (matchstr != result[index])
{
return false;
}
}
else
{
if(mapPattern.ContainsValue(result[index]))
{
return false;
}
mapPattern.Add(c, result[index]);
}
++index;
}
return true;
}
}
The approach I have currently looks up the Dictionary
twice to see if it already exists as a key
or as a value
in the Dictionary
, which I believe would be the reason for slowing this by a significant amount.
Can you determine if I can do away with looking up twice? This solution only runs better than around 36% of the other submissions for this current problem. So, I believe there must be a better and faster way.
Split()
can be removed. (Not sure how much it will save you). 2) Try resubmitting the same code a few times. I have received a large variation on the performance \$\endgroup\$