7

LeetCode 第205题 Isomorphic Strings

 3 years ago
source link: https://codechina.org/2019/08/leetcode-205-isomorphic-strings-java/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

来源:https://leetcode.com/problems/isomorphic-strings/

题目:同模式字符串

给定两个字符串s和t,判断他们是否模式相同。

两个字符串的模式相同的意思是s的字符可以经过替换变成t。

所有出现的字符,必须被另外一个字符替换,保持原有的顺序。两个不同的字符,不能用同一个字符替换,但是一个字符可以用自己本身替换。

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

注意:
你可以假定s和t的长度相等。


直接看起来这个比较比较麻烦。一种思路就是在s遇到一个不重复的字符就替换成t对应位置的字符,依次类推,如果最后替换的结果和t完全相等,那么就是同模式的字符。这个思路写起来有点麻烦。

我的思路是用hashmap来存储每个字符串第一个不重复字符出现的位置,这样就可以把字符串给变成一个数字数组,这样就得到了字符串的模式,如果两个字符串的模式相同,那么两个字符串就是同模式字符串。

例如例1的egg,按照这个思路,就会变成[0,1,1],而add也会变成[0,1,1],所以他们是同模式字符串。

例2的foo模式也是[0,1,1],但是bar是[0,1,2],所以他们不是同模式字符串。

所以代码分为两个部分,第一个部分把字符串转换成模式数字数组。

index-1.png

第二个部分比较两个模式数组是否相同:

main-4.png

Github:https://github.com/tinyfool/leetcode/tree/master/src/p0205

本题属于哈希表类题目,想了解更多关于哈希表的题目,可以参看哈希表专题


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK