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.

给定两个字符串,判断它们是否属于同构词。我们借助一个map和一个set,map用来存放两个字符串中对应字符的关系,set用来存放map中的value。题目假设两个字符串长度相同,假设我们比较到了第i个字符,如果map中已经存放了key为s.chatAt(i)的键值对,我们就比较t.charAt(i)与get(s.charAt(i))是否相等,如果不等,就返回false,如果相等就继续搜索。如果map中没有存放key为s.charAt(i)的键值对,我们此时要判断map中的value是否有t.charAt(i),如果set中已经存在t.charAt(i), 直接返回false;否则将这一个键值对放入map中,并且把value放入set中。代码如下:
public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> hm = new HashMap<Character, Character>();
        Set<Character> set = new HashSet<Character>();
        for(int i = 0; i < s.length(); i++) {
            if(hm.containsKey(s.charAt(i))) {
                if(hm.get(s.charAt(i)) != t.charAt(i))
                    return false;
            } else {
                if(set.contains(t.charAt(i))) {
                    return false;
                } else {
                    hm.put(s.charAt(i), t.charAt(i));
                    set.add(t.charAt(i));
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2277302