[LeetCode-JAVA] 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保存映射,同时还要判断value是否被映射过,用set进行过滤

代码:

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map = new HashMap<Character, Character>();
        Set<Character> set = new HashSet<Character>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < len ; i++){
            if(!map.containsKey(s.charAt(i))){
                if(!set.contains(t.charAt(i))){  //过滤 value t
                    map.put(s.charAt(i), t.charAt(i));  // s -> t
                    set.add(t.charAt(i));
                }
                else
                    return false;
            }
            sb.append(map.get(s.charAt(i)));    
        }
        return sb.toString().equals(t);
    }
}

 

posted @ 2015-06-02 10:23  可爱的波儿胖  阅读(144)  评论(0编辑  收藏  举报

友情链接 : CodeForge源码分享