« Back
read.

Leetcode 205 Isomorphic Strings.

Leetcode 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.


Basic solution with HashMap:

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map map=new HashMap<>();
        Map map2=new HashMap<>();
        String[] sword=s.split("");
        String[] tword=t.split("");

        for(int i=0;i < sword.length;i++){
            if(!map.containsKey(sword[i])){
                map.put(sword[i],tword[i]);
            }else{
                if(!map.get(sword[i]).equals(tword[i])){
                    return false;
                }
            }

        }
        for(int i=0;i < tword.length;i++){
            if(!map2.containsKey(tword[i])){
                map2.put(tword[i],sword[i]);
            }else{
                if(!map2.get(tword[i]).equals(sword[i])){
                    return false;
                }
            }

        }
        return true;
    }
}

Another way without using HashMap(comes from Leetcode discussion):


public class Solution {
    public boolean isIsomorphic(String s1, String s2) {
        int[] m = new int[512];
        for (int i = 0; i < s1.length(); i++) {
            if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
            m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
        }
        return true;
    }
}
comments powered by Disqus