LeetCode 205. 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.

题意:给定两个字符串s和t,判断它们是否是同构的。
note:假设s和t长度相同。
类似中文中ABB、ABAB类型的词语。

思路:利用ASCII码表中字符和int型数值的对应关系。
先将大小为128的数组中元素全部初始化为0.
分别遍历两个字符串s和t,分别从s和t中取出一个字符,然后判断数组中下标为该字符对应的ASCII码值的元素是否相等。
例:s.charAt(i)='a',则s.charAt(i)对应的ASCII码值为97,即num1[s.charAt(i)]等价于num1[97]
若相等,则将数组中该处的元素值更新为i+1,即相当于字符在字符串中的下标+字符在字符串中的出现次数。
其实就相当于将字符强制转换为int型数值,数组中存储的为字符在字符串中的下标跟字符在字符串中的出现次数之和。

ASCII第一次以规范标准的类型发表是在1967年,最后一次更新则是在1986年,至今为止共定义了128个字符;其中33个字符无法显示(一些终端提供了扩展,使得这些字符可显示为诸如笑脸、扑克牌花式等8-bit符号),且这33个字符多数都已是陈废的控制字符。控制字符的用途主要是用来操控已经处理过的文字。在33个字符之外的是95个可显示的字符。用键盘敲下空白键所产生的空白字符也算1个可显示字符(显示为空白)。

摘自维基百科

public boolean isIsomorphic(String s, String t) {
        int[] num1 = new int[128];
        int[] num2 = new int[128];
        for(int i = 0; i < s.length(); i++){
            if(num1[s.charAt(i)] != num2[t.charAt(i)])
                return false;
            num1[s.charAt(i)] = i + 1;
            num2[t.charAt(i)] = i + 1;
        }
        return true;
    }

参考:https://leetcode.com/problems/isomorphic-strings/discuss/57796/My-6-lines-solution

原文地址:https://www.cnblogs.com/zeroingToOne/p/8536773.html