您的位置:首页 > 其它

205. Isomorphic Strings

2017-09-27 18:53 239 查看
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.public class Solution {
/*
* 思路:利用一个Map来辅助解决问题,Map的key为s中的字符,Map的value为t中与之对应的字符
* 循环遍历s(题目中已经假设s和t长度相同),
* 如果遍历到的字符在Map中存在,则检测它对应的value
* 是否为t中对应的字符,是则继续,不是则直接返回false;
* 如果遍历到的字符在Map中不存在,先检测Map的vlaue中是否包含t对应的字符,如果包含
* 直接返回false,如果不包含,则将s,t中对应的字符put进Map
*
*/
public boolean isIsomorphic(String s, String t) {
if (s==null || s.length()<=1) {
return true;
}
Map<Character, Character> map = new HashMap<Character, Character>();
for (int i=0; i<s.length(); i++) {
Character a = s.charAt(i);
Character b = t.charAt(i);
if (map.containsKey(a)) {
if (map.get(a).equals(b)) {
continue;
} else {
return false;
}
} else {
if (!map.containsValue(b)) {
map.put(a, b);
} else {
return false;
}
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: