[LeetCode]205. Isomorphic Strings 解题报告(C++)
题目描述
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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
题目大意
- 判断两个字符串是否同构.
解题思路
方法1:
- 判断字符串是否同构. 两个字符串相同位置的字符应该能够互相替换.
- 由于ASCII码只有256个.用256大小的数组代替哈希表.并初始化为0.
- 遍历字符串.按索引位置各取出一个字符.若其对应哈希表相同.则更新哈希值为i+1
- 否则不同就是说二者非同构.
代码实现:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = { 0 }, m2[256] = { 0 };
int 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;
}
};
小结
- 方法1:每次更新索引位置上的字符的哈希表.. 太厉害了.