同构字符

同构字符

一、题目描述

给定两个字符串,判断是否时两个同类型的字符串。同类型指的时如ABB,ABAB等。
实例:

输入:s = "egg", t = "add"
输出:true

输入:s = "foo", t = "bar"
输出:false

输入:s = "paper", t = "title"
输出:true

二、解题思路

只需要考虑字符串的形式,无需考虑具体字符。可以遍历字符串,将每个字符串转成aabb的形式,在比较是否相等。

三,解题方法

创建两个map集合,将map1中每个键存为s字符串的每个字符,val对应t中的字符。map2则相反。只需要判断map1中value的值与map2中key的值是否相等。再反过来map2中的即可。
代码实现:

class Solution {
    public boolean isIsomorphic(String s, String t) {

        Map<Character,Character> map1 = new HashMap<Character,Character>();
        Map<Character,Character> map2 = new HashMap<Character,Character>();
        if(s.length() != t.length()){
            return false;
        }
        for(int i=0;i<s.length();i++){
            char sChar = s.charAt(i);
            char tChar = t.charAt(i);

            if(map1.containsKey(sChar) && map1.get(sChar) != tChar){
                return false;
            }

            if(map2.containsKey(tChar) && map2.get(tChar) != sChar){
                return false;
            }
            
            map1.put(sChar,tChar);
            map2.put(tChar,sChar);
            
        }

        return true;
    }
}
posted @ 2022-10-21 00:38  z_coding  阅读(34)  评论(0)    收藏  举报