[Leetcode] 205. Isomorphic Strings 解题报告

来源:互联网 发布:网络性能管理系统 编辑:程序博客网 时间:2024/06/05 20:26

题目

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.

思路

哈希表的典型应用。需要注意的是,我们需要进行双向验证。否则对于aa和ba这样的例子而言,如果只从aa向ba验证,结果就不对了。

代码

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

原创粉丝点击