Easy-题目46:205. Isomorphic Strings

来源:互联网 发布:mac如何卸载opera 编辑:程序博客网 时间:2024/06/04 18:11

题目原文:
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%

0 0
原创粉丝点击