【leetcode】205. Isomorphic Strings

一、题目描述

Given two strings s and t, determine if they are isomorphic.

Two strings 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.

For example,
Given "egg""add", return true.

Given "foo""bar", return false.

Given "paper""title", return true.

Note:
You may assume both s and t have the same length.


题目解读:判断两个字符串是否是同构的


思路:每个字符的位置和出现次数是关键信息,使用map存储当前字符出现的位置


c++代码(108ms,5.99%)

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1=s.size();
        int len2=t.size();
        if(len1 != len2)
            return false;
        map<char,int> location1; //存每个字符出现的位置
        map<char,int> location2;
        for(int i=1;i<=len1;i++){
            if(location1[s[i-1]] != 0 || location2[t[i-1]] != 0)
                if(location1[s[i-1]] != location2[t[i-1]])
                    return false;
            location1[s[i-1]] = i;
            location2[t[i-1]] = i;
        }//for
        return true;
    }
};


自己写的代码运行时间那么长,排名也靠后。一看就知道还有更优化的方法。

看一下别人的代码,很巧妙的利用数组把位置信息存进去了。

数组的256是因为字符的ASCII码的范围。

在计算机内部,所有的信息最终都表示为一个二进制的字符串,每一个二进制位有0和1两种状态,一个字节一共可以用来表示256种不同的状态,每一个状态对应一个符号,就是256个符号,从00000000到11111111。


代码如下:(8ms,69.48%)

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int m1[256] = {0}, m2[256] = {0}, n = s.size();
        for (int i = 0; i < n; ++i) {
            if (m1[s[i]] != m2[t[i]]) return false;
            m1[s[i]] = i + 1;
            m2[t[i]] = i + 1;
        }
        return true;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值