p205

LeetCode p205 Isomorphic Strings 题解

1.题目:

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.

题意:

输入两个字符串,判断一个是否他们是否同构,及字符能够完全映射。

2.解题思路:

记录每个字符上次出现的位置,比较。
// ASCII 256个

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
public class Solution {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length())
return false;
int[] ak = new int[256 * 2];
for (int i = 0; i < s.length(); i++) {
if (ak[s.charAt(i)] != ak[t.charAt(i) + 256])
return false;
ak[s.charAt(i)] = i + 1; // 因为初始化全为0这里加一区分
ak[t.charAt(i) + 256] = i + 1;
}
return true;
}
}

4.一些总结: