leetcode 205. Isomorphic Strings

来源:互联网 发布:淘宝卖家怎么认证 编辑:程序博客网 时间:2024/06/14 02:50

1.题目

判断两个字符串是否通过
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.
字符串S中的所有字符都可以用对应的字符替换来得到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.两个字符串长度相等。

2.分析

字符是一一对应的映射关系。即如果a对应b,那么在字符串S中,a出现的位置,在T中对应b出现的位置。

因此遍历字符串,记录对应字符出现的位置。

3.代码

bool isIsomorphic(string s, string t) {    int* pos1 = new int[256]();    int* pos2 = new int[256]();    for (int i = 0; i < s.size(); i++) {        if (pos1[s[i]] != pos2[t[i]])            return false;        pos1[s[i]] = i + 1;        pos2[t[i]] = i + 1;    }    return true;}

在discuss中看见了Python的一个很巧妙的解法,因为字符是一一对应的关系,那么用set去重

def isIsomorphic(s, t):    print len(set(zip(s,t)))==len(set(s))==len(set(t))
原创粉丝点击