码迷,mamicode.com
首页 > 其他好文 > 详细

同构string

时间:2015-05-28 07:05:18      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

leetcode新题,另外似乎是L家面经题

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.

Note:
You may assume both s and t have the same length.

这里注意不能s中两个char map到t中相同char,所以同时还需要check当前t[i]是否已经对应其他char了,这样就需要两个map来保存map pair的关系

例如 ab, aa return false 

技术分享
 1  //use hashmap to record map of (s, t)
 2     public static boolean isIsomorphic(String s, String t) {
 3         if(s == null && t == null) {
 4             return true;
 5         }
 6         if(s.length() != t.length()) {
 7             return false;
 8         }
 9         
10         HashMap<Character, Character> map1 = new HashMap<Character, Character>();//s[i], t[i]
11         HashMap<Character, Character> map2 = new HashMap<Character, Character>();//t[i], s[i]
12         
13         
14         for(int i = 0; i < s.length(); i++){
15             char schar = s.charAt(i);
16             char tchar = t.charAt(i);
17             
18             if(!map1.containsKey(schar)){
19                 map1.put(schar, tchar);
20             }else if(map1.get(schar) != tchar) return false; // map to wrong char
21             
22             //check no two map to same char in t
23             if(!map2.containsKey(tchar)){
24                 map2.put(tchar, schar);
25             }else if(map2.get(tchar) != schar) return false;
26         }
27         
28         return true;
29     }
View Code

 

同构string

标签:

原文地址:http://www.cnblogs.com/xiaomaoliu/p/4534899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!