LeetCode205 Isomorphic Strings

LeetCode205 Isomorphic Strings

Description

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.

For example,
Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

Note:
You may assume both s and t have the same length.

The signature of the C++ function:bool isIsomorphic(string s, string t)

题解

  • 分析
    字符之间的一一映射问题。

样例

输入(s)输入(t)结果
aaabfalse
abcatrue
abaafalse
  • 思路
    建立一张128个节点的有向图,每个节点代表一个字符。s和t中第i个字符s[i]、t[i]定义了顶点s[i]到t[i]的一条边。每顶点的入度和出度都不能超过1,否则就不是一一映射。
    因为每个顶点的出度和入度都不能超过1,所以可以直接用连个表来保存所有信息。

核心代码

    vector<int> outLink(128, -1);
    vector<int> inLink(128, -1);

    for (int i = 0; i < s.size(); i++)
    {
        char sc = s[i];
        char tc = t[i];

        if (outLink[sc] == -1 && inLink[tc] == -1)
        {
            outLink[sc] = tc;
            inLink[tc] = sc;
        }
        else
            if (!((outLink[sc] == tc) && (inLink[tc] == sc)))
                return false;
    }

    return true;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值