[leetcode] 205. Isomorphic Strings

来源:互联网 发布:淘宝怎么和快递合作 编辑:程序博客网 时间:2024/05/16 17:17

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.

这道题是判断两个字符串是否是同构字符串,题目难度为Easy。


题目比较简单,典型用Hash Table的题目,需要注意要双向比较。这里不必真的用Hash Table,用长度256的数组即可,效率比Hash Table要高。具体代码:

class Solution {public:    bool isIsomorphic(string s, string t) {        vector<int> hash1(256, 256), hash2(256, 256);        for(int i=0; i<s.size(); ++i) {            if(hash1[s[i]] == 256 && hash2[t[i]] == 256) {                hash1[s[i]] = t[i];                hash2[t[i]] = s[i];            }            else if(hash1[s[i]] == t[i]) continue;            else return false;        }        return true;    }};

0 0
原创粉丝点击