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

Example 2:

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

Example 3:

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

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

 

简述:

给定相同长度字符串s,t,判断字符串s是否可以通过字符替换成t(不能将两个不同字符替换成同一个字符)。

 

解题思路:


通过map保存字符的替换情况,因为不能将两个不同字符替换成同一字符,即字符替换是一对一映射。使用两个map维持这种一对一映射关系。使用m1,m2分别保存串s,t的替换关系,遍历串s,将s[i]替换为t[i],如当前替换关系存在冲突,返回false。若能顺利遍历完两个串,返回true。

    bool isIsomorphic(string s, string t) {
        map<char, char> m1, m2; 
        for(int i=0; i<s.length(); ++i) { 
            if((m1.find(s[i]) == m1.end()) && (m2.find(t[i])==m2.end())) {
                m1[s[i]] = t[i];
                m2[t[i]] = s[i];
            } else if((m1.find(s[i]) != m1.end()) && (m2.find(t[i]) != m2.end())){
                if((m1[s[i]] != t[i]) || (m2[t[i]] != s[i])) return false;
            } else {
                return false;
            }
        }
        
        return true;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值