LeetCode #205 - 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.

Example 1:

Input: s = "egg", t = "add"

Output: true

Example 2:

Input: s = "foo", t = "bar"

Output: false

Example 3:

Input: s = "paper", t = "title"

Output: true

Note:
You may assume both and have the same length.

判断两个字符串是否同构,定义两个哈希表,存储每个字母上一次出现的位置,遍历到当前字母时,比较两个字母分别在两个字符串上一次出现的位置是否一样,不一样就肯定不是同构。

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

猜你喜欢

转载自blog.csdn.net/lawfile/article/details/81174661