205. Isomorphic Strings(easy)

Easy

829240FavoriteShare

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.

 

C++: 

/*
 * @Author: SourDumplings
 * @Date: 2019-08-18 09:40:41
 * @Link: https://github.com/SourDumplings/
 * @Email: changzheng300@foxmail.com
 * @Description: https://leetcode.com/problems/isomorphic-strings/
 */
class Solution
{
public:
    bool isIsomorphic(string s, string t)
    {
        int l = s.length();
        if (l != t.length())
        {
            return false;
        }

        map<char, char> m1, m2;
        for (int i = 0; i < l; i++)
        {
            if (m1.find(s[i]) == m1.end())
            {
                if (m2.find(t[i]) != m2.end())
                {
                    return false;
                }

                m1[s[i]] = t[i];
                m2[t[i]] = s[i];
            }
            else
            {
                if (m1[s[i]] != t[i])
                {
                    return false;
                }
            }
        }
        return true;
    }
};

Java:

import java.util.Hashtable;
import java.util.Map;

/*
 * @Author: SourDumplings
 * @Date: 2019-08-18 10:00:02
 * @Link: https://github.com/SourDumplings/
 * @Email: changzheng300@foxmail.com
 * @Description: https://leetcode.com/problems/isomorphic-strings/
 */

class Solution
{
    public boolean isIsomorphic(String s, String t)
    {
        int l = s.length();
        if (l != t.length())
        {
            return false;
        }
        Map<Character, Character> m1 = new Hashtable<>();
        Map<Character, Character> m2 = new Hashtable<>();
        for (int i = 0; i < l; i++)
        {
            Character c1 = s.charAt(i);
            Character c2 = t.charAt(i);
            if (m1.containsKey(c1))
            {
                if (m1.get(c1) != c2)
                {
                    return false;
                }
            }
            else
            {
                if (m2.containsKey(c2))
                {
                    return false;
                }
                m1.put(c1, c2);
                m2.put(c2, c1);
            }
        }
        return true;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值