LeetCode205 Isomorphic Strings
Description
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.
The signature of the C++ function:bool isIsomorphic(string s, string t)
题解
- 分析
字符之间的一一映射问题。
样例
输入(s) | 输入(t) | 结果 |
---|---|---|
aa | ab | false |
ab | ca | true |
ab | aa | false |
- 思路
建立一张128个节点的有向图,每个节点代表一个字符。s和t中第i个字符s[i]、t[i]定义了顶点s[i]到t[i]的一条边。每顶点的入度和出度都不能超过1,否则就不是一一映射。
因为每个顶点的出度和入度都不能超过1,所以可以直接用连个表来保存所有信息。
核心代码
vector<int> outLink(128, -1);
vector<int> inLink(128, -1);
for (int i = 0; i < s.size(); i++)
{
char sc = s[i];
char tc = t[i];
if (outLink[sc] == -1 && inLink[tc] == -1)
{
outLink[sc] = tc;
inLink[tc] = sc;
}
else
if (!((outLink[sc] == tc) && (inLink[tc] == sc)))
return false;
}
return true;