标签:mission href lan ant foo data- nbsp cond submit
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.
Approach #1: C++.
class Solution {
public:
bool isIsomorphic(string s, string t) {
int len = s.size();
int ArrS[256] = {0};
int ArrT[256] = {0};
for (int i = 0; i < len; ++i) {
if (charArrS[s[i]] != charArrT[t[i]]) {
return false;
}
ArrS[s[i]] = i + 1;
ArrT[t[i]] = i + 1;
}
return true;
}
};
Approach #2: Java.
class Solution {
public:
bool isIsomorphic(string s, string t) {
int len = s.size();
int ArrS[256] = {0};
int ArrT[256] = {0};
for (int i = 0; i < len; ++i) {
if (charArrS[s[i]] != charArrT[t[i]]) {
return false;
}
ArrS[s[i]] = i + 1;
ArrT[t[i]] = i + 1;
}
return true;
}
};
Approach #3: Python.
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
arrS = {}
arrT = {}
for i, val in enumerate(s):
arrS[val] = arrS.get(val, []) + [i]
for i, val in enumerate(t):
arrT[val] = arrT.get(val, []) + [i]
return sorted(arrS.values()) == sorted(arrT.values())
| Time Submitted | Status | Runtime | Language |
|---|---|---|---|
| a few seconds ago | Accepted | 236 ms | python |
| 5 minutes ago | Accepted | 8 ms | java |
| 13 minutes ago | Accepted | 4 ms | cpp |
Analysis:
标签:mission href lan ant foo data- nbsp cond submit
原文地址:https://www.cnblogs.com/ruruozhenhao/p/9945634.html