首页 > 其他 > 详细

【LeetCode】205 - Isomorphic Strings

时间:2015-09-09 22:41:40      阅读:222      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!