Java Solution with two hashMap


  • 0
    S

    public class Solution {
    public boolean isIsomorphic(String s, String t) {
    Map <Character,Integer> hash1 = new HashMap<Character,Integer>();
    Map <Character,Integer> hash2 = new HashMap<Character,Integer>();

            for(int i=0; i<s.length();i++){
                char ch1 = s.charAt(i);
                char ch2 = t.charAt(i);
                
                if(hash1.containsKey(ch1)){
                    if(t.charAt(hash1.get(ch1)) != t.charAt(i))
                        return false;
                }else{
                    if(hash2.containsKey(ch2))
                        return false;
                    hash1.put(ch1,i);
                    hash2.put(ch2,i);
                }
            }
            return true;
        }
    }

  • 0
    S

    i do not think two hash map is necessary,one is enough~


  • 0
    S

    i do not think two hash map is necessary,one is enough~

    my code:

    public boolean isIsomorphic(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        
        Map<Character,Character> map = new HashMap<Character,Character>();
        int len = s.length();
        for(int i=0;i<len;i++){
            Character c = map.get(s.charAt(i));
            if(c == null){
                if(map.containsValue(t.charAt(i))){ //注意判断之前有没有存在该值
                    return false;
                }
                map.put(s.charAt(i),t.charAt(i));
            }else if(c!=t.charAt(i)){
                return false;
            }
        }
        return true;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.