Leetcode/Top Interview 150

[Hashmap][Easy] 290. Word Pattern

자전거통학 2024. 5. 6. 09:12

https://leetcode.com/problems/word-pattern/description

 

Q. pattern과 단어 문자열 s 가 주어질때, 패턴과 문자열이 일치하는지 판단하라. 

 

 

Solution. 

 최대한 단순하게 접근하고 TC는 O(N)으로 제한한다. 

 

 우선 s의 단어셋과 pattern의 길이가 다르면 무조건 일치하지 않게 된다. 

 

 다음으로 s의 단어셋을 풀어 hashset을 만들어 놓는다. 이 수대로 다른 단어가 존재 한다는 것이다. 

 

 마지막으로 pattern을 순회하며, 각 패턴의 캐릭터 별로 단어가 일치하는지 확인한다. 

 

 모두 통과하고 hashset의 수가 패턴의 단어수와 같다면, 일치하는 것으로 판단할 수 있다.

 

더보기

 

public bool WordPattern(string pattern, string s) 
{
    string[] words = s.Split(' ');
    if(pattern.Length != words.Length)
        return false;

    HashSet<string> hsWords = new HashSet<string>();
    for(int q = 0; q < words.Length; ++q)
    {
        if(!hsWords.Contains(words[q]))
            hsWords.Add(words[q]);
    }

    Dictionary<char, string> dictCache = new Dictionary<char, string>();
    for(int q = 0; q < pattern.Length; ++q)
    {
        char cur = pattern[q];
        if(dictCache.ContainsKey(cur))
        {
            if(words[q] != dictCache[cur])
                return false;
        }
        else dictCache.Add(cur, words[q]);
    }
    return hsWords.Count==dictCache.Count;
}

 

결과.