《leetCode》:Isomorphic Strings

来源:互联网 发布:关于知乎的诗词 编辑:程序博客网 时间:2024/05/20 16:33

题目

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.

思路

借用HashMap即可完成,但是要注意的是:Map虽然保证了键的唯一,但是我们还要保证键值中的值唯一,即不可以有多个键对应 一个值。

public boolean isIsomorphic(String s, String t) {        if(s==null&&t==null){            return true;        }        int len1=s.length();        int len2=t.length();        if(len1!=len2){            return false;        }        Map<Character,Character> map=new HashMap<Character,Character>();        StringBuffer sb=new StringBuffer();        for(int i=0;i<len1;i++){            char ch=map.getOrDefault(s.charAt(i), '\0');            if(ch=='\0'){//第一次出现,则保存                //保存之前要检查,键值中的值是否唯一,即不能多个不同的键映射到一个值                char tempCh=t.charAt(i);                if(map.containsValue(tempCh)){                    return false;                }                map.put(s.charAt(i),tempCh);//只有键和值都没有出现,才加入map                sb.append(tempCh);            }            else{                sb.append(ch);            }        }        if(t.equals(sb.toString())){            return true;        }        return false;    }
1 0
原创粉丝点击