Easy 205题 Isomorphic Strings

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 map=new HashMap();
        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



你可能感兴趣的:(leetcode,easy)