Leetcode205.同构字符串

题目链接:205.同构字符串
代码:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()) return false;
        char[] map = new char[128];
        int[] set = new int[128];
        for(int i=0; i<s.length(); i++){
            if(map[s.charAt(i)] != '' && map[s.charAt(i)] != t.charAt(i)){
                return false;
            }
            if(map[s.charAt(i)] == '' && set[t.charAt(i)] == 1){
                return false;
            }
            map[s.charAt(i)] = t.charAt(i);
            set[t.charAt(i)] = 1;
        }
        return true;
    }
}

笔记

  • 输入数据只局限于字符串,那么可以直接使用长度为128的数组对输入的字符进行存储。使用集合类会影响速度,将集合类改为数组后,运行时间变化为22ms -> 11ms。
  • 事实证明,直接访问数组比使用集合类的操作来得更快。将输入的字符串改为字符数组 char[] ss = s.toCharArray();后,运行时间变化为11ms->4ms。
原文地址:https://www.cnblogs.com/liuyongyu/p/14196684.html