leetcode 205

Posted

tags:

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

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.

设定两个字符串长度相等,所谓的“同构”,就是字符串 s 中的字符可以一对一的映射到字符串 t 中的字符。不能一对多,也不能多对一。

利用两个map实现。

代码如下:                                

 

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         map<char, char> mapA;
 5         map<char, char> mapB;
 6         int n = s.length();
 7         for(int i = 0; i < n; i++)
 8         {
 9             char ss = s[i];
10             char tt = t[i];
11             map<char, char>::iterator it = mapA.find(ss);
12             if(it != mapA.end())
13             {
14                 if(mapA[ss] != tt)
15                 {
16                     return false;
17                 }
18             }
19             else
20             {
21                 map<char, char>::iterator ii = mapB.find(tt);
22                 if(ii != mapB.end() && mapB[tt] != ss)
23                 {
24                     return false;
25                 }
26                 else
27                 {
28                     mapA[ss] = tt;
29                     mapB[tt] = ss;
30                 }
31             }
32         }
33         return true;
34     }
35 };

 

 

                                                                                                                        

 

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

Leetcode 205. Isomorphic Strings

Java [Leetcode 205]Isomorphic Strings

leetcode 205

205. Isomorphic Strings - LeetCode

205. Isomorphic Strings(LeetCode)

LeetCode 205. Isomorphic Strings