205. Isomorphic Strings

2018/04/13 leetcode 共 755 字,约 3 分钟

Title

the problem link

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.

题目大意: 就是一一对应,这个映射关系是双向的,因此不能用map做,用的map只能判断单向的关系,第一次没ac,看solution的映射关系为字符对应到最后一次出现的索引位置,这个就合理了,真机智。

这种题目还挺多的,以后得多看下

Solution

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

Search

    Table of Contents