你的位置:首页 > Java教程

[Java教程][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.

 

     个人觉得挺有意思的一道题。首先要理解到底啥才叫lsomorphic strings。归纳出其的特点。

     其实就是字母可以不相同,但是结构必须相同。就是说对于string s,其出现重复字母的index必须和string t,出现重复的字母的index相等而且数量也相同。

     搞清楚这个就可以用if statement来写判断了。

      代码如下。~

 

public class Solution {  public boolean isIsomorphic(String s, String t) {    if(s.length()!=t.length()) return false;    HashMap<Character,Integer> smap=new HashMap<>();    HashMap<Character,Integer> tmap=new HashMap<>();    for(int i=0;i<s.length();i++){      if(!smap.containsKey(s.charAt(i))){        if(tmap.containsKey(t.charAt(i))){          return false;        }      }else{        int index=smap.get(s.charAt(i));        if(!tmap.containsKey(t.charAt(i))||tmap.get(t.charAt(i))!=index){          return false;        }      }      smap.put(s.charAt(i),i);      tmap.put(t.charAt(i),i);    }    return true;  }}