205. Isomorphic Strings

一、题目

  1、审题

  

  2、分析

    判断等长的字符串 s 与 t ,其中的字符是否有一一对应的关系。其中 s 中的一个字符只能对应对应 t 中的特定的一个字符。

二、解答

  1、思路:

    方法一、

    使用一个 Map , key 为 s 中的字符, value 为 t 中的字符。

    过程如下;

      、判断 Map 中是否存在 key,

        若不存在,判断是否存在此 value;

          若存在,则返回 false;

           否则,放入此 key-value。

        若存在,判断对应的 value 是否和 t 的字符相同,

          若是,则继续遍历;

          否则,返回 false;

    public boolean isIsomorphic(String s, String t) {
        // 1、替换字符
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            String str1 = s.substring(i, i + 1);
            String str2 = t.substring(i, i + 1);
            if(!map.containsKey(str1)) {
                // 2、是否有重复的 value
                if(map.values().contains(str2))    
                    return false;
                map.put(str1, str2);
            } else if(!(map.get(str1).equals(str2))) {
                return false;
            }
        }
        
        return true;
    }

  方法二、

    ①、创建两个整形数组 m1 与 m2,分别存放 s 中字符对应 ASCII 值对应的 s 的下标,和 t 中字符对应 ASCII 值对应的下标,且初值均为 0;

    ②、遍历 s 与 t 中字符,判断这两个字符对应的数组值是否相等,若不相等,则返回 false, 否则赋给当前下标。

    注意: 为了区别下标为 0 的字符,存储在数组中的下标值从 1 开始

    public boolean isIsomorphic(String s, String t) {
       int len = s.length();
        int[] m1 = new int[256];
        int[] m2 = new int[256];
        
        for (int i = 0; i < len; i++) {
            char c1 = s.charAt(i);
            char c2 = t.charAt(i);
            if(m1[c1] != m2[c2])
                return false;
            m1[c1] = i + 1;
            m2[c2] = i + 1;
        }
        return true;
    }
原文地址:https://www.cnblogs.com/skillking/p/9829453.html