LeetCode 205 Isomorphic Strings

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 205 Isomorphic Strings相关的知识,希望对你有一定的参考价值。

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.

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

 

思路:

这道题要在两个字符串的字符之间建立一对一的映射,不允许一对多和多对一映射的出现。因此,可以建立一个关联两个字符串字符的map,检查是否现有键的对应值于当前值冲突,并设立一个set,检查未被存入map的键其对应值是否已经在set中出现,在二者均不出现的情况下返回true。

 

解法:

 1 import java.util.Map;
 2 import java.util.Set;
 3 
 4 public class Solution
 5 {
 6     public boolean isIsomorphic(String s, String t)
 7     {
 8         if(s == null || t == null)
 9             return false;
10         if(s.length() != t.length())
11             return false;
12 
13         Map<Character, Character> map = new HashMap<>();
14         Set<Character> set = new HashSet<>();
15 
16         char[] sArray = s.toCharArray();
17         char[] tArray = t.toCharArray();
18 
19         for(int i = 0; i < s.length(); i++)
20         {
21             if(map.containsKey(sArray[i]))
22             {
23                 if(map.get(sArray[i]) != tArray[i])
24                     return false;
25             }
26             else
27             {
28                 if(set.contains(tArray[i]))
29                     return false;
30                 else
31                 {
32                     map.put(sArray[i], tArray[i]);
33                     set.add(tArray[i]);
34                 }
35             }
36         }
37 
38         return true;
39     }
40 }

 

以上是关于LeetCode 205 Isomorphic Strings的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 205. Isomorphic Strings

LeetCode 205 Isomorphic Strings

LeetCode 205 Isomorphic Strings

[LeetCode] 205 Isomorphic Strings

LeetCode 205. Isomorphic Strings

LeetCode205. Isomorphic Strings 解题小结