码迷,mamicode.com
首页 > 其他好文 > 详细

205. Isomorphic Strings

时间:2018-10-18 16:51:37      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:paper   lse   must   input   apt   question   amp   iso   tle   

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.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:
You may assume both and have the same length.

 

//Time: O(n), Space: O(n)   
 public boolean isIsomorphic(String s, String t) {
        if (s == null && t == null) {
            return true;
        }
        
        if (s == null || t == null) {
            return false;
        }
        
        if (s.length() != t.length()) {
            return false;
        }
        
        int[] mapS = new int[256];
        int[] mapT = new int[256];
        
        for (int i = 0; i < s.length(); i++) {
            if (mapS[s.charAt(i)] != mapT[t.charAt(i)]) {
                return false;
            }
            mapS[s.charAt(i)] = i + 1;//反例就是ab和aa,否则无法判断第一位有无出现过
            mapT[t.charAt(i)] = i + 1;
        }
        
        return true;
    }

 

205. Isomorphic Strings

标签:paper   lse   must   input   apt   question   amp   iso   tle   

原文地址:https://www.cnblogs.com/jessie2009/p/9810062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!