145.Isomorphic Strings(同构串)

题目:

Given two strings s and t, determine if they are isomorphic.

给定两个字符串s和t,确定它们是否是同构的。

Two strings are isomorphic if the characters in s can be replaced to get t.

如果s中的字符可以替换为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.

您可以假设s和t都具有相同的长度。

解答:

 1 class Solution {
 2     public boolean isIsomorphic(String s, String t) {
 3         int[] maps=new int[256];
 4         int[] mapt=new int[256];
 5         for(int i=0;i<s.length();i++){
 6             if(maps[s.charAt(i)]!=mapt[t.charAt(i)]) return false;
 7             else{
 8                 maps[s.charAt(i)]=i+1;
 9                 mapt[t.charAt(i)]=i+1;
10             }
11         }
12         return true;
13     }
14 }

详解:

s和t中的字母要有一对一的映射关系,可以用两个hashmap来记录s和t中的字符和出现次数的情况,这里可以用数组代替hashmap

s和t长度相同,遍历s时,分别从s和t中取出一个字符,查找数组的值,如果不相等,返回false;如果相等,个数加1

posted @ 2018-09-08 10:18  chan_ai_chao  阅读(402)  评论(0编辑  收藏  举报