首页 > 其他 > 详细

[LeetCode]Isomorphic Strings

时间:2015-11-14 23:15:19      阅读:287      评论: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.

解题思路:

用哈希表来存储字符出现的位置,然后比较同型字符出现的位置,如果不等返回false。

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         int len = s.size();
 5         
 6         unordered_map<int, int> cache1;
 7         unordered_map<int, int> cache2;
 8         for (int i = 0; i < len; ++i) {
 9             auto c1 = cache1.find(s[i]);
10             auto c2 = cache2.find(t[i]);
11             
12             if (c1 == cache1.end() && c2 == cache2.end()) {
13                 cache1[s[i]] = i;
14                 cache2[t[i]] = i;
15             } else if ((c1 == cache1.end() && c2 != cache2.end()) || 
16                       (c1 != cache1.end() && c2 == cache2.end()) || 
17                       (c1->second != c2->second)) {
18                 return false;
19             }
20         }
21         
22         return true;
23     }
24 };

 

[LeetCode]Isomorphic Strings

原文:http://www.cnblogs.com/skycore/p/4965243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!