[leetcode] 205. Isomorphic Strings

来源:互联网 发布:淘宝拍卖房产过户 编辑:程序博客网 时间:2024/05/29 03:57

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.

解法一:

建立hash table,看s[i]是否出现过,如果没有,将t[i]的值作为s[i]的映射。如果出现过,检验t[i]是否与s[i]的映射相同。对s->t, t->s各做一次循环。

class Solution {public:    bool isIsomorphic(string s, string t) {        int m[256] = {0};        for(int i=0; i<s.size();++i){            if(!m[s[i]]) m[s[i]] = t[i];            else{                if (m[s[i]]!=t[i]) return false;            }        }                int n[256] = {0};        for(int i=0; i<s.size();++i){            if(!n[t[i]]) n[t[i]] = s[i];            else{                if (n[t[i]]!=s[i]) return false;            }        }                return true;            }};


解法二:

核心在于m[s[i]] = i + 1; n[t[i]]= i + 1。

class Solution {public:    bool isIsomorphic(string s, string t) {        int m[256] = {0}, n[256] = {0};        for(int i=0; i<s.size();++i){            if (m[s[i]] != n[t[i]]) return false;            m[s[i]] = i + 1;            n[t[i]] = i + 1;        }                return true;            }};



0 0
原创粉丝点击