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

LeetCode OJ:Isomorphic Strings(同构字符串)

时间:2015-12-25 22:19:29      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

看两个字符串是否同构,用map就可以解决,不过要注意双向都要检查,代码如下:

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         map<char, char> m1;
 5         map<char, char> m2;
 6         if(s.size() != t.size())
 7             return false;
 8         for(int i = 0; i < s.size(); ++i){
 9             if(m1.find(s[i]) == m1.end() && m2.find(t[i]) == m2.end()){
10                 m1[s[i]] = t[i];
11                 m2[t[i]] = s[i];
12             }
13             else if(m1.find(s[i]) != m1.end() && m2.find(t[i]) != m2.end()){
14                 if(m1[s[i]] != t[i] || m2[t[i]] != s[i])
15                     return false;
16             }else{
17                 return false;
18             }
19         }
20         return true;
21     }
22 };

 

LeetCode OJ:Isomorphic Strings(同构字符串)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4987700.html

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