首页 > 其他 > 详细

[lintcode]638.Strings Homomorphism

时间:2017-10-24 16:46:52      阅读:210      评论: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.

注意事项:

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

样例:

Given s = "egg", t = "add", return true.

Given s = "foo", t = "bar", return false.

Given s = "paper", t = "title", return true.

解题思路:

一开始我一直钻到牛角尖里面,一直想着字母一一对应的替换。

最近在看算法,这道题应该算是一道很简单的哈希表。

其实就是要记录每一个字母出现的次数和它对应的位置。

以egg和add为例:

‘g‘和‘d‘出现了两次,就是[1,2,2],[1,2,2]

‘foo‘:[1,2,2];bar:[1,1,1]

然后我又再一次陷入了这个存数组的漩涡里面。。。我试图搞一个数组,按照index把出现次数存进去。。。

后来在网上搜索了一下,其实只要按照string的顺序(位置对应),读出每一个char的出现次数(次数对应)就可以以了。

 1 class Solution {
 2 public:
 3     /*
 4      * @param s: a string
 5      * @param t: a string
 6      * @return: true if the characters in s can be replaced to get t or false
 7      */
 8     bool isIsomorphic(string s, string t) {
 9         // write your code here
10        map <char, int> word1,word2; //<key:char类型,value:int类型>
11        for(int i = 0; i<s.size(); i++){
12            word1[s[i]]++;
13            word2[t[i]]++;
14        }
15        for(int i = 0; i< s.size(); i++){
16            if(word1[s[i]]!=word2[t[i]]){
17                return false;
18            }
19        }
20        return true;
21     }
22 };

 

[lintcode]638.Strings Homomorphism

原文:http://www.cnblogs.com/hopping/p/7724342.html

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