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

[LeetCode] Isomorphic Strings

时间:2015-04-29 13:36:44      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

解题思路:

这道题是判断两个单词是否同构。这里的同构的意思是,对于例子egg和add,若存在一个映射,e->a,g->d,单词egg和add同构。注意,不可以多个字符映射到同一个字符中去,比如aa和ab。因此要有两个hash表来记录。由于是字符,不会超过256个,因此可以用数组来记录这种映射。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1=s.length();
        int len2=t.length();
        if(len1!=len2){
            return false;
        }
        char charMap[256];
        char charMap1[256];
        memset(charMap, 0, sizeof(char)*256);
        memset(charMap1, 0, sizeof(char)*256);
        for(int i=0; i<len1; i++){
            if(charMap[s[i]]==0){
                charMap[s[i]] = t[i];
            }else if(charMap[s[i]]!=t[i]){
                return false;
            }
            if(charMap1[t[i]]==0){
                charMap1[t[i]] = s[i];
            }else if(charMap1[t[i]]!=s[i]){
                return false;
            }
        }
        return true;
    }
};


[LeetCode] Isomorphic Strings

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45364995

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