一、题目描述
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.
题目解读:判断两个字符串是否是同构的
思路:每个字符的位置和出现次数是关键信息,使用map存储当前字符出现的位置
c++代码(108ms,5.99%)
class Solution {
public:
bool isIsomorphic(string s, string t) {
int len1=s.size();
int len2=t.size();
if(len1 != len2)
return false;
map<char,int> location1; //存每个字符出现的位置
map<char,int> location2;
for(int i=1;i<=len1;i++){
if(location1[s[i-1]] != 0 || location2[t[i-1]] != 0)
if(location1[s[i-1]] != location2[t[i-1]])
return false;
location1[s[i-1]] = i;
location2[t[i-1]] = i;
}//for
return true;
}
};
自己写的代码运行时间那么长,排名也靠后。一看就知道还有更优化的方法。
看一下别人的代码,很巧妙的利用数组把位置信息存进去了。
数组的256是因为字符的ASCII码的范围。
在计算机内部,所有的信息最终都表示为一个二进制的字符串,每一个二进制位有0和1两种状态,一个字节一共可以用来表示256种不同的状态,每一个状态对应一个符号,就是256个符号,从00000000到11111111。
代码如下:(8ms,69.48%)
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = {0}, m2[256] = {0}, n = s.size();
for (int i = 0; i < n; ++i) {
if (m1[s[i]] != m2[t[i]]) return false;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return true;
}
};