<LeetCode OJ> 205. Isomorphic Strings

来源:互联网 发布:优化电脑最好的软件 编辑:程序博客网 时间:2024/05/16 13:03

205. Isomorphic Strings

Total Accepted: 46971 Total Submissions: 163994 Difficulty: Easy

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.


分析:

问题就出在有相同字符的地方,利用哈希map建立字符与位置的关系,如果字符重复的话,位置会变。

举例:

Given "egg", "add", return true.
   1,先压入哈希map中得到每个字符及其对应的位置,011,011,

   2,接着判断每个字符的位置是否一样011=011,所以true
Given "foo", "bar", return false.
   1,压入哈希map得到位置序列,011,012
   2,判断位置是否相等011!=012,所以false

class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.size()!=t.size())            return false;        unordered_map<char,int> mapsing,mapting;        for(int i=0;i<s.size();i++)        {            mapsing[s[i]]=i;            mapting[t[i]]=i;         }        for(int i=0;i<s.size();i++)        {            if(mapsing[s[i]]!=mapting[t[i]])                return false;        }        return true;        }};


优化一下:更加耗时了,不解中......

class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.size()!=t.size())            return false;        unordered_map<char,int> mapsing,mapting;        for(int i=0;i<s.size();i++)        {            if(mapsing[s[i]]!=mapting[t[i]])                return false;            mapsing[s[i]]=i+1;//这里之所以+1,是因为防止和初始值0相巧合,比如aa和ab            mapting[t[i]]=i+1;         }        return true;        }};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50463166

原作者博客:http://blog.csdn.net/ebowtang

1 0