[LeetCode] Isomorphic Strings

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

[LeetCode] Isomorphic Strings

Given two stringssandt, determine if they are isomorphic.

Two strings are isomorphic if the characters inscan be replaced to gett.

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; }}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航