码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 205

时间:2016-11-14 11:57:49      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:false   nbsp   code   string   i++   aced   etc   iso   多对一   

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

标签:false   nbsp   code   string   i++   aced   etc   iso   多对一   

原文地址:http://www.cnblogs.com/shellfishsplace/p/6050946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!