标签: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.
Note:
You may assume both s and t have the same length.
题意:判断两个字符串同形字符串,就是说,将s中的字符替换为t中的相应字符,能够保证s中不同的字符替换成t中的不同的字符,可以想象成一个加密过程,利用某种映射,将s加密成t
public class Solution {
public boolean isIsomorphic(String s, String t) {
//利用map保存映射关系
Map<Character,Character> map = new HashMap<Character,Character>();
for(int i = 0 ; i < s.length() ; i ++){
char key = s.charAt(i);
char value = t.charAt(i);
if(map.containsKey(key)){
if(value != map.get(key)){//存在一条key->x的映射,且x != value
return false;
}
}else if(map.containsValue(value)){
return false;//已经存在一条x->value的映射,但是x != key
}else{//不存在key->x映射和x->value的映射
map.put(key,value);
}
}
return true;
}
}LeetCode OJ 205 Isomorphic Strings
标签:leetcode isomorphic strings
原文地址:http://blog.csdn.net/havedream_one/article/details/45458465