[LeetCode] 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.

 

思路:需要两个方向的映射,从s-t  和从 t-s  。判断之前对应的字符是不是一致,由于存在  “ab” 与“aa”这样的情况,从s到t需要两个映射,而从t到s只需一个映射。

时间复杂度:O(n)

代码:

    public boolean isIsomorphic(String s, String t) {

         if(s==null || t==null || s.length()!=t.length()) return false;

         Map<Character, Character> maps=new  HashMap<Character, Character>();

         Map<Character, Character> mapt=new  HashMap<Character, Character>();

         for(int i=0;i<s.length();i++)

         {

             if(!maps.containsKey(s.charAt(i)))

                 maps.put(s.charAt(i), t.charAt(i));

             else

             {

                 if(maps.get(s.charAt(i)).charValue()!=t.charAt(i))

                     return false;

             }

             if(!mapt.containsKey(t.charAt(i)))

                 mapt.put(t.charAt(i), s.charAt(i));

             else 

             {

                 if(mapt.get(t.charAt(i)).charValue()!=s.charAt(i))

                     return false;                 

             }

         }

         if(maps.size()!=mapt.size())

             return false;

         return true;

    }

优化:

扩展:

 

你可能感兴趣的:(LeetCode)