美文网首页
[Leetcode] 205. Isomorphic Strin

[Leetcode] 205. Isomorphic Strin

作者: gammaliu | 来源:发表于2016-04-13 21:52 被阅读0次
    1. 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.

    Subscribe to see which companies asked this question

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            Set<Character> usedSet = new HashSet<>();
            Map<Character,Character> charMap = new HashMap<>();
            for(int i = 0; i < s.length(); i++){
                Character ch = charMap.get(s.charAt(i));
                Character si = s.charAt(i);
                Character ti = t.charAt(i);
                if(ch == null){
                    if(usedSet.contains(ti) == false){
                        charMap.put(si, ti);
                        usedSet.add(ti);
                    }
                    else return false;
                }
                else{
                    if(ch != ti) return false;
                }
            }
            return true;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:[Leetcode] 205. Isomorphic Strin

          本文链接:https://www.haomeiwen.com/subject/vjhglttx.html