[Leetcode学习-java&c++]Isomorphic Strings

46 篇文章 0 订阅

问题:

难度:easy

说明:

比较下两个字符串是不是同构的,就是两个字符串,如果不一定完全一致,但是构造形式相似就行。

题目连接:https://leetcode.com/problems/isomorphic-strings/

输入范围:

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

输入案例:

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

我的代码:

加一个双向的映射 Map 即可,要注意是256的长度,因为输入是所有 ascii 的编码字符。

Java:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int lens = s.length(), lent = t.length();
        if(lens != lent) return false;
        char[] chs = s.toCharArray(), cht = t.toCharArray();
        int mapStoT[] = new int[256], mapTtoS[] = new int[256];
        Arrays.fill(mapStoT, -1);
        Arrays.fill(mapTtoS, -1);
        for(int i = 0; i < lens; i ++) {
            int ts = (int)chs[i], tt = (int)cht[i];
            if(mapStoT[ts] == -1 && mapTtoS[tt] == -1) {
                mapStoT[ts] = tt;
                mapTtoS[tt] = ts;
            } else {
                if(mapStoT[ts] != tt || mapTtoS[tt] != ts) return false;
            }
        }
        return true;
    }
}

C++:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int lens = s.length(), lent = t.length();
        if(lens != lent) return false;
        int mapStoT[256], mapTtoS[256];
        memset(mapStoT, -1, sizeof(mapStoT)), memset(mapTtoS, -1, sizeof(mapTtoS));
        for(int i = 0; i < lens; i ++) {
            int ts = (int)s[i], tt = (int)t[i];
            if(mapStoT[ts] == -1 && mapTtoS[tt] == -1) {
                mapStoT[ts] = tt;
                mapTtoS[tt] = ts;
            } else if(mapStoT[ts] != tt || mapTtoS[tt] != ts) return false;
        }
        return true;
    } 
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值