205. Isomorphic Strings

来源:互联网 发布:欧洲经济一体化数据 编辑:程序博客网 时间:2024/06/08 13:24

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to gett.

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.


判断两个字符串形式是不是一样。比如"egg""add",都是122这种形式。首先将字符串都转化成数字数组表达的形式,比如paper的形式就是12134,使用map来进行字符和数字的映射。然后对比转换得来的数组判断。


代码:

class Solution{public:bool isIsomorphic(string s, string t) {vector<int> v1 = toArray(s);vector<int> v2 = toArray(t);for(int i = 0; i < s.size(); ++i){if(v1[i] != v2[i]) return false;}return true;}private:vector<int> toArray(string s){int cnt = 0;vector<int> res(s.size());map<char, int> m;for(int i = 0; i < s.size(); ++i){if(m.find(s[i]) == m.end()){m[s[i]] = cnt++;}res[i] = m[s[i]];}return res;}};


原创粉丝点击