Leetcode/Top Interview 150

[Hashmap][Easy] 205. Isomorphic Strings

자전거통학 2024. 5. 4. 23:18

https://leetcode.com/problems/isomorphic-strings/description

 

Q. 두개의 문자열 s 와 t 가 주어 질때, isomorphic 한지 판단하라. 

 

Solution. 

 즉, 캐릭터의 출현 빈도, 변환된 위치 등이 같다면 isomorphic 하다고 할 수 있겠다.

 

 여러가지 방법을 활용 할 수 있겠다.

 최대한 간단하게 freq buffer와 위치 체크 등을 이용한다. 

 

더보기
public bool IsIsomorphic(string s, string t) 
{
    if(s.Length != t.Length)
        return false;

    Dictionary<char, int> dictFreqS = new Dictionary<char, int>();
    for(int q = 0; q < s.Length; ++q)
    {
        char cur = s[q];
        if(dictFreqS.ContainsKey(cur))
            ++dictFreqS[cur];
        else 
            dictFreqS.Add(cur, 1);
    }

    Dictionary<char, int> dictFreqT = new Dictionary<char, int>();
    for(int q = 0; q < t.Length; ++q)
    {
        char cur = t[q];
        if(dictFreqT.ContainsKey(cur))
            ++dictFreqT[cur];
        else 
            dictFreqT.Add(cur, 1);
    }

    Dictionary<char, char> dictMap = new Dictionary<char, char>();
    for(int q = 0; q < t.Length; ++q)
    {
        char cur = s[q];
        if(!dictMap.ContainsKey(cur))
            dictMap.Add(cur, t[q]);
        else 
        {
            if(dictMap[cur] != t[q])
                return false;
        }

        if(dictFreqS[s[q]] != dictFreqT[t[q]])
            return false;
    }
    return true;
}

 

 

결과. 

'Leetcode > Top Interview 150' 카테고리의 다른 글

[Hashmap][Easy] 242. Valid Anagram  (0) 2024.05.06
[Hashmap][Easy] 290. Word Pattern  (0) 2024.05.06
[Hashmap][Easy] 383. Ransom Note  (0) 2024.05.04
[Matrix][Medium] 289. Game of Life  (0) 2024.05.04
[Matrix][Medium] 36. Valid Sudoku  (0) 2024.05.04