大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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.
Input: s = "egg", t = "add"
Output: true
Input: s = "foo", t = "bar"
Output: false
Input: s = "paper", t = "title"
Output: true
1 <= s.length <= 5 * 10^4
t.length == s.length
s
and t
consist of any valid ascii character.首先先簡單的翻譯一下題目
給兩個字串,要判斷對應的字有沒有一對多,有的話回傳false,沒有的話回傳true。
作法大致上是這樣
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
dict = {}
for index in range(len(s)):
#print(dict)
if s[index] not in dict:
if t[index] in dict.values():
# print(t[index], ":", dict.values())
return False
dict[s[index]] = t[index]
else:
if dict[s[index]] != t[index]:
return False
if t[index] in dict.values():
return False
#print(dict)
return True
bool isIsomorphic(char * s, char * t){
int pair_s[128] = {0};
int pair_t[128] = {0};
for (int i=0 ; i<strlen(s) ; i++){
int index_s = (int)(s[i]);
int index_t = (int)(t[i]);
// printf("%d, %d\n", index_s, index_t);
if (pair_s[index_s] == 0 && pair_t[index_t] == 0){
pair_s[index_s] = index_t;
pair_t[index_t] = index_s;
// printf("%d: %d, %d: %d\n", index_s, pair_s[index_s], index_t, pair_t[index_t]);
} else {
if (pair_s[index_s] == index_t && pair_t[index_t] == index_s){
continue;
} else {
return false;
}
}
}
return true;
}
Python
C
大家明天見