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

【LeetCode】205 - Isomorphic Strings

时间:2015-09-09 22:42:42      阅读:136      评论: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 "foo", "app"; returns true we can map f -> a and o->p
given "bar", "foo"; returns false we can‘t map both ‘a‘ and ‘r‘ to ‘o‘

given "ab", "ca"; returns true we can map ‘a‘ -> ‘b‘ and ‘c‘ -> ‘a‘

Solution 1: map

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.size()!=t.size())return false;
        map<char, char> m;
        for(int i=0;i<s.size();i++){
            if(!m.count(s[i])){
                map<char,char>::const_iterator iter=m.begin();
                while(iter!=m.end()){
                    if(iter->second==t[i])return false;
                    iter++;
                }
                m.insert(make_pair(s[i], t[i]));
            }else{
                if(m[s[i]]!=t[i])return false;
            }
        }
        return true;
    }
};

Solution 2:

bool isIsomorphic(string s, string t) {
if(s.size()!=t.size()) return false;
map<char,char> map1;
map<char,char> map2;

for(int i=0;i<s.length();i++){
char c1=s[i];
char c2=t[i];
if(map1.count(c1)){
if(map1[c1]!=c2) return false;
}
if(map2.count(c2)){
if(map2[c2]!=c1) return false;
}

map1.insert(c1, c2);
map2.insert(c2, c1);
}
return true;
}

【LeetCode】205 - Isomorphic Strings

标签:

原文地址:http://www.cnblogs.com/irun/p/4796061.html

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