【leetcode】Isomorphic Strings

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.

分析:

由于两个字符串等长,设定一个二维数组step[150][2],第一维的下标对应字符的ascii码,,第二维的第一个数为标志位,第二个数为对应字符的差值。

从s的第一个字符开始遍历,将数组中ascii对应的位置标志位置1,代表该字符已经出现过,并计算与t对应字符的差,保存。

对于之后的字符,首先判断是否在之前出现过,如果没有,重复上一步,否则,判断s中该字符与t中对应字符的差是否与已保存的差值相等,如果不等,返回false


class Solution {
public:
    bool isIsomorphic(string s, string t) {
int steps[150][2]={0};
	int stept[150][2]={0};
	for(int i=0;i<s.length();i++)
	{
		if (!steps[s[i]][0]&&!stept[t[i]][0])
		{
			steps[s[i]][1]=(float)fabs((float)s[i]-t[i]);
			steps[s[i]][0]=1;

			stept[t[i]][1]=(float)fabs((float)s[i]-t[i]);
			stept[t[i]][0]=1;

		}
		else
			if ((float)fabs((float)s[i]-t[i])!=steps[s[i]][1])
			{
				return false;
			}

	}
	return true;
    }
};
出现的问题:

1、一开始没有考虑到其他类型字符,所以将s[i]与‘a’做差了。其实没必要,直接用s[i]的值即可/

2、一些不一样的测试例子,比如输入ab与aa,根据规则,a与a对应后,b不能再对应a。因此在做判断时,不仅要判断s中的该字符是否出现过,也要判断t中是否出现过对应后的字符。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值