马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Judie 于 2023-5-23 02:21 编辑
Given two strings s and t, determine if they are isomorphic.
Two strings s and t 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
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
class Solution {
public:
bool isIsomorphic(string s, string t) {
}
};
Judyclass Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
d = {}
for x, y in zip(s, t):
if x not in d:
if y not in d.values():
d[x] = y
else:
return False
elif d[x] != y:
return False
return True
Gray
c++ bad version?#include <iostream>
#include <map>
#include <algorithm>
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char,char> dict;
for(int i = 0; i < s.size(); i++){
vector<char> value;
for(auto it = dict.cbegin(); it != dict.cend(); ++it){
value.push_back(it->second);
}
if (dict.find(s[i])!=dict.end()){
s[i] = dict[s[i]];
}else {
cout << "cycle" << endl;
for(int j = 0; j < value.size();j++){
if(value[j] == t[i]){
return false;
}
}
dict[s[i]] = t[i];
s[i] = t[i];
}
}
if(s == t){
return true;
}else {
return false;
}
}
};
c++ better version?#include <iostream>
#include <map>
#include <algorithm>
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char,char> dict;
for(int i = 0; i < s.size(); i++){
vector<char> value;
if (dict.find(s[i])!=dict.end()){
s[i] = dict[s[i]];
}else {
for(auto it = dict.cbegin(); it != dict.cend(); ++it){
if(it->second == t[i]){
return false;
}
}
dict[s[i]] = t[i];
s[i] = t[i];
}
}
if(s == t){
return true;
}else {
return false;
}
}
};
|