205.leetcode Isomorphic Strings (easy)[map结构 字符串处理]

来源:互联网 发布:添加URL端口 编辑:程序博客网 时间:2024/05/20 05:03

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.

题目想要判断两个字符串是否是同构的,同构的字符串用其中一个字符串中相应的字符替换两一个字符串中对应位置的字符可以得到与之前的字符串相同的字符串。因此解题思想是同构的字符串首先长度必须相同,用两个map分别存放每个位置的char与对应的位置值,然后遍历字符串对当前字符检查在之前的字符中位置是否一致。

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



0 0
原创粉丝点击