Easy 205题 Isomorphic Strings

来源:互联网 发布:java整型转16进制 编辑:程序博客网 时间:2024/05/16 08:17

Question:

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.


Solution:

public class Solution {    public boolean isIsomorphic(String s, String t) {        Map<Character,Character> map=new HashMap<Character, Character>();        if(s.length()!=t.length())            return false;        int len=s.length();        for(int i=0;i<=len-1;i++)        {            char sa=s.charAt(i);            char ta=t.charAt(i);            if(map.containsKey(sa))            {                if(!(map.get(sa)==ta))                    return false;            }            else            {                if(map.containsValue(ta))                    return false;                map.put(sa,ta);            }        }        return true;    }}
discuss里有一个很简单的方法,但是需要搞懂,put的返回值是什么,如果put了一个原来没有的key,则返回值为null;如果put了一个原来有的key,则返回旧的value,这里就是老key的位置
public boolean isIsomorphic(String s, String t) {    Map m = new HashMap();    for (Integer i=0; i<s.length(); ++i)        if (m.put(s.charAt(i), i) != m.put(t.charAt(i)+"", i))            return false;    return true;}



0 0
原创粉丝点击