leetcode 205: 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 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.

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

[思路]

建1个map保存映照关系, 同时用1个set保持 被映照的char, 保证同1个char 不会被映照两次.

[CODE]

public class Solution {
//test case: "egg", "add"

public boolean isIsomorphic(String s, String t) {
//init check
if(s==null || t==null) return false;
if(s.length() != t.length()) return false;

Map<Character, Character> map = new HashMap<Character, Character>();
Set<Character> set = new HashSet<Character>();

for(int i=0; i<s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);

if(map.containsKey(c1)) {
if(map.get(c1) != c2) return false;
} else {
if(set.contains(c2)) return false;
else {
map.put(c1, c2);
set.add(c2);
}
}
}
return true;
}
}

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » leetcode 205: Isomorphic Strings

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡