205. Isomorphic Strings
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
分析
一开始想着发现一共字符串相同的字符的位置,然后试图在另外一个字符串里面对应位置确定是不是也有相同字符串,但位置多变,而且字符和字符之间没有固定的对应关系,就陷入了死胡同。看了大神的评论,恍然大悟,直呼内行。
大神的思路是用两个大小为256的数组,初始化全为0,用嵌套数组的方法,同时遍历两个字符串,若遍历完两个256大数组的比较一直相等,则两个字符串为同构字符串,输出true,否则输出false。其中妙就秒在不用考虑字符之间的映射关系,即大小为256的数组的索引由字符的ASCII构成,只需要比较m[256]与n[256]对应的数值即可。
代码
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m[256] = { 0 };
int n[256] = { 0 };
for (int i = 0; i < s.size(); i++) {
// 首次都为0,其后若字符串结构不同,+1的次数不同,必然导致
// 以下判断成立,则输出false
if (m[s[i]] != n[t[i]]) {
return false;
}
m[s[i]] += 1;
n[t[i]] += 1;
}
return true;
}
};
int main() {
Solution solution;
string s = "paper";
string t = "title";
solution.isIsomorphic(s, t) ? cout << s <<" is isomorphic to " <<t<< endl : cout << s << " is not isomorphic to " << t << endl;
return 0;
}
复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n) | O(1) |