LeetCode_Isomorphic Strings

本文深入探讨了如何通过映射关系识别两个字符串是否同构,并提供了Java代码实现。详细阐述了同构字符串的概念,包括映射规则、避免一对多或多对一的映射情况,以及使用Java中的Map容器进行高效映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

判断两个字符串是否同构:s中的每个字符按顺序映射到t中一个字符,映射关系不能是一对多,例如"foo"和"bar",按顺序映射:f->b,o->a,o->r,o同时对a和r,所以foo和egg不是同构的;同理,不能多对一,即s中不同字符不能对应t中相同的字符,例如,"ab"和"aa",a->a,b->a,a和b同时对应a,所以ab和aa不符合条件。

以s中的每个字符作为key,t中的每个字符作为value,利用Java中的map容器做映射。

public class Solution {
    public boolean isIsomorphic(String s, String t) {
    Map<Character,Character> mp1 = new HashMap<>();
		final int len1 = s.length();
		final int len2 = s.length();
		if(len1!=len2) return false;
		if(len1==0) return true;
		for(int i = 0;i < len1;i++)
		{
			if(!mp1.containsKey(s.charAt(i)))
			{
				mp1.put(s.charAt(i),t.charAt(i));
				for(int j = 0;j<i;j++)
				{
					if(mp1.get(s.charAt(i))==mp1.get(s.charAt(j)))//多对一
					{
						return false;
					}
				}
			}
			else
			{
				if(mp1.get(s.charAt(i))!=t.charAt(i))//一对多
				{
					return false;
				}
			}
		}
        return true;
    }
}
时间复杂度较高,期待更高效的方法。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值