Isomorphic Strings

题目来源
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,t到s的映射关系,假如关系不对,就返回false。虽然A了,但是还是有点乱…再想想。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int n = s.size();
        unordered_map map1;
        unordered_map map2;
        for (int i=0; i

然后实际上只需要记录当前字母前一次出现的位置就可以了,代码如下:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int n = s.size();
        vector m1(256, 0);
        vector m2(256, 0);
        for (int i=0; i

你可能感兴趣的:(Isomorphic Strings)