Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

同构字符串 #9

Open
Aras-ax opened this issue Mar 5, 2019 · 0 comments
Open

同构字符串 #9

Aras-ax opened this issue Mar 5, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Mar 5, 2019

给定两个字符串 s 和 t,判断它们是否是同构的。

如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

示例 1:

输入: s = "egg", t = "add"
输出: true

示例 2:

输入: s = "foo", t = "bar"
输出: false

示例 3:

输入: s = "paper", t = "title"
输出: true

说明:

  • 你可以假设s 和 t 具有相同的长度。

解答

// 解法一
function isSame(s1, s2) {
    if (s1.length !== s2.length) {
        return false;
    }

    let hashA = {},
        hashB = {};
    for (let i = 0; i < s1.length; i++) {
        let a = s1[i],
            b = s2[i];

        if (hashA[a] === hashB[b]) {
            hashA[a] = hashB[b] = (hashB[b] || 0) + 1;
            continue;
        }
        return false;
    }
    return true;
}

//解法二
function isSame(s1, s2) {
    if (s1.length !== s2.length) {
        return false;
    }

    let hashA = {},
        hashB = {};
    for (let i = 0; i < s1.length; i++) {
        let a = s1[i],
            b = s2[i];

        if (!hashA[a] && !hashB[b]) {
            hashA[a] = b;
            hashB[b] = a;
        } else if (hashA[a] !== b || hashB[b] !== a) {
            return false;
        }
    }

    return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant