205. Isomorphic Strings

来源:互联网 发布:ubuntu 15.04 vim配置 编辑:程序博客网 时间:2024/05/21 22:56

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.

题意:计算两个字符串是否同构。注意:你可以假设两个字符串的长度一致。

思路:将字符串转换为对应的数字组合,然后判断是否相同,如:egg->122, add->122同构;foo->122,bar->123,不同构。

class Solution {public:bool isIsomorphic(string s, string t) {if (s.empty() && t.empty())return true;int *s_num, *t_num;getIsomorphic(s, s_num);getIsomorphic(t, t_num);for (int i = 0; i < s.size(); i++){if (s_num[i] != t_num[i])return false;}return true;}int getIsomorphic(string s, int*& s_num){map<char, int> myMap;s_num = new int[s.size()];int val = 1;for (int i = 0; i < s.size(); i++){char ch = s[i];if (myMap.insert(pair<char, int>(ch, val)).second){s_num[i] = val;val++;}else{s_num[i] = myMap[ch];}}return 0;}};



0 0
原创粉丝点击