LeetCode | Isomorphic Strings

来源:互联网 发布:怎么成为域名注册局 编辑:程序博客网 时间:2024/06/08 04:02

题目


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.


分析与思路


方法一


刚看到这个问题的时候,想法比较直接,同构也就是说s中字符相同的两个位置上,t中的相应字符也应该是相同的;s中字符不同的两个位置上,t中相应字符也不一样。

为了减少查找的次数,将与当前字符相同的位都置上标记,以后就不用再查找。

具体代码为:

bool isIsomorphic(string s, string t){unsigned int length = s.size();if(length != t.size())return false;bool* flag = (bool*)malloc (sizeof(bool)*length);memset(flag,false,sizeof(flag));for(int i=0;i<length;i++){if(flag[i] == true)continue;flag[i] = true;char c = s.at(i);for(int j=i+1;j<length;j++){if(s.at(j) - c == 0){flag[j] = true;if(t.at(j) - t.at(i) != 0)return false;}elseif(t.at(j) - t.at(i) == 0)return false;}}return true;}

但是这样的程序性能是O(n^2)的,在leetcode上的执行时间是 28ms 很不理想

方法二


考虑到ASC字符总共也只有256个,因此,可以用Hash表来表示s中字符与t中字符的对应关系。具体方法是:
声明一个char型数组hash1[],大小是256,初值全为NULL(即0),hash1[ s[i] ]表示s[i]在t中对应的字符。
声明一个bool型数组hash2[],大小是256,初值全为false,hash2[ t[i] ]表示s[i]在t中对应的字符t[i]是否出现过。

代码:

bool isIsomorphic(string s, string t){char hash1[256]={NULL};//init the hash1 table with 0bool hash2[256]={false};//init the hash2 table with falseunsigned int length = s.size();if(length != t.size())return false;for(int i=0; i<length; i++){if(hash1[s.at(i)] != NULL){if(hash1[s.at(i)] != t.at(i))return false;}else{if(hash2[t.at(i)] == 1)return false;hash1[s.at(i)] = t.at(i);hash2[t.at(i)] = true;}}return true;}

这种做法在leetcode上的时间是8ms。

方法三


后来想寻找更快的方法,在http://www.cnblogs.com/easonliu/p/4465650.html上看到了这个做法,不过leetcode要92ms,性能很差。

代码:

class Solution {public:    bool isIsomorphic(string s, string t) {        if (s.length() != t.length()) return false;        map<char, char> mp;        for (int i = 0; i < s.length(); ++i) {            if (mp.find(s[i]) == mp.end()) mp[s[i]] = t[i];            else if (mp[s[i]] != t[i]) return false;        }        mp.clear();        for (int i = 0; i < s.length(); ++i) {            if (mp.find(t[i]) == mp.end()) mp[t[i]] = s[i];            else if (mp[t[i]] != s[i]) return false;        }        return true;    }};


0 0
原创粉丝点击