iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


205. Isomorphic Strings

Question

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

Example1

Input: s = "egg", t = "add"
Output: true

Example2

Input: s = "foo", t = "bar"
Output: false

Example3

Input: s = "paper", t = "title"
Output: true

Constraints

  • 1 <= s.length <= 5 * 10^4
  • t.length == s.length
  • s and t consist of any valid ascii character.

解題

題目

首先先簡單的翻譯一下題目
給兩個字串,要判斷對應的字有沒有一對多,有的話回傳false,沒有的話回傳true。

Think

作法大致上是這樣

  • 就是上面提到的一樣,把讀進來的每一個字元去判斷有沒有一對多,有的話回傳false,沒有的話回傳true。
  • C的陣列長度設128是因為我看最一開始的ASCII的字元是0~127。

Code

Python

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

C

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;
}

Result

  • Python

  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 17 - Remove Duplicates from Sorted List
下一篇
Day 19 - Integer to Roman
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言