您的位置:首页 > 其它

LeetCode - Isomorphic Strings

2015-04-30 16:03 253 查看
Isomorphic Strings

2015.4.30 15:54

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.

Solution:

  Think about the string pair "abb" and "cdd". An isomorphic pair is like one-to-one mapping. So we use the basic priniciple: injective + surjective = bijective.

  Check if the mapping from s to t is onto, and t to s as well. If both hold, they're isomorphic.

Accepted code:

#include <cstring>
using namespace std;

class Solution {
public:
bool isIsomorphic(string s, string t) {
return check(s, t) && check(t, s);
}
private:
bool check(string s, string t) {
char a[256];

memset(a, 0, sizeof(a));
int i;
int n = s.length();

for (i = 0; i < n; ++i) {
if (a[s[i]] == 0) {
a[s[i]] = t[i];
}
s[i] = a[s[i]];
}

return s == t;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: