ACM준비/LeetCode

205. Isomorphic Strings

조규현15 2024. 4. 3. 23:53
반응형

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

205. Isomorphic Strings
Easy
Topics
Companies
Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

 

주어진 두 문자열 ( A, B ) 의 구성에서 대치 ( a - b ) 가 이뤄져 동일한 구조 임을 확인하는 내용입니다.


Example 1:

Input: s = "egg", t = "add"
Output: true
Example 2:

Input: s = "foo", t = "bar"
Output: false
Example 3:

Input: s = "paper", t = "title"
Output: true
 

Constraints:

1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.

 

주어지는 두 문자열의 크기는 같고, ascii 문자임을 확인합니다.

 

풀이는 순회 탐색 ( N ) 에서 문자 ( char ) 를 MappingTable 에 넣어 대치가 가능한 지 판별합니다.

중간에 대치가 불가능한 경우 결과는 실패입니다.

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isIsomorphic = function (s, t) {
    const mapping_table_st = {};
    const mapping_table_ts = {};
    for (let i = 0; i < s.length; i++) {
        const char_s = s[i];
        const char_t = t[i];
        if (!mapping_table_st[char_s]) {
            mapping_table_st[char_s] = char_t;

            if (mapping_table_ts[char_t]) return false;

            mapping_table_ts[char_t] = char_s;
        }

        if (mapping_table_st[char_s] != char_t) return false;
    }
    return true;
};

 

반응형

'ACM준비 > LeetCode' 카테고리의 다른 글

2542. Maximum Subsequence Score  (0) 2023.05.25
703. Kth Largest Element in a Stream  (0) 2023.05.23