Day 18 - Isomorphic Strings

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题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


<<:  [Lesson18] Dagger

>>:  Day 21网路通讯协定

[Day25] 透过GCP实作(1/4):透过Cloud Function直接拉取资料

接下来这几天,将会带领各位以GCP的架构的视角。 向各位阐述我们先前进行的DialogFLow F...

Day17【Web】网路攻击:点击劫持 Clickjacking

点击劫持 点击劫持(Clickjacking) 技术又称为 界面伪装攻击(UI redress at...

Day 11-制作购物车系统之安装及资料夹结构(一)

今天要开始制作购物车系统所需的VScode环境。 GO GO ~ 以下内容有参考教学影片,底下有附网...

Day 09: 机器学习你知多少?

人工智慧? 机器学习? 深度学习? 刚踏入机器学习的学生自然会对这些专有名词感到相当模糊,我们就先来...

RISC-V on Rust 从零开始(6) - 使用Spike模拟器

其实RISC-V官方也有开发了一个instruction accurate等级的模拟器Spike,只...