Leetcode - Find and Replace Pattern
Leetcode - Word Pattern

Leetcode - Isomorphic Strings

violet posted @ Apr 29, 2020 08:09:58 AM in 算法 with tags Algorithm Golang hash , 179 阅读

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

Given two strings s and t, determine if they are isomorphic.

Two strings 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.

Example 1:

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

 

func isIsomorphic(s string, t string) bool {
    if len(s) != len(t) {
        return false
    }
    hash1 := map[byte]byte{}
    hash2 := map[byte]byte{}
    for i := 0; i < len(s); i++ {
        w1 := s[i]
        w2 := t[i]
        if _, ok := hash1[w1]; !ok {
            hash1[w1] = w2
        }
        if _, ok := hash2[w2]; !ok {
            hash2[w2] = w1
        }
        if hash1[w1] != w2 || hash2[w2] != w1 {
            return false
        }
    }
    
    return true
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter