Easy-题目46:205. 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.
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..
题目大意:
给出字符串s和t,判断他们是不是同构(isomorphic)的。
同构的定义是s和t具有相同的结构,即可用t串一个字符代替s串的一个字符,而其他字符不变。
例如,”egg”和 ”add”是同构的;”foo”和”bar”不是同构的;”paper”和”title ”是同构的。
保证s串和t串的长度相等。
题目分析:
使用一个HashMap记录一组key-value对,key为s串中每个字符,value为t串中每个字符。如果出现相同的key则不是同构的。
例如s=”foo”,t=”bar”,则存在o-b和o-r两个同key的映射。
但这样还不够,还要再按相同方法建立t串到s串的map,因为若s=”bar”,t=”foo”则不存在s串到t串中的相同key,但存在t串到s串的相同key。
源码:(language:java)

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        int slen=s.length();
        int tlen=t.length();
        if(slen!=tlen)
            return false;
        else
        {
            HashMap<Character,Character> map=new HashMap();
            for(int i=0;i<slen;i++)
            {
                if(!map.containsKey(s.charAt(i)))
                    map.put(s.charAt(i),t.charAt(i));
                else
                {
                    if(map.get(s.charAt(i)) != t.charAt(i))
                        return false;
                }
            }
            map.clear();
            for(int i=0;i<slen;i++)
            {
                if(!map.containsKey(t.charAt(i)))
                    map.put(t.charAt(i),s.charAt(i));
                else
                {
                    if(map.get(t.charAt(i)) != s.charAt(i))
                        return false;
                }
            }
            return true;            
        }
    }
}

成绩:
34ms,beats 30.09%,众数26ms,8.93%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值