同构字符串 Isomorphic Strings

本文介绍了一种通过使用两个HashMap来判断两个字符串是否为同构字符串的方法。此方法的时间复杂度为O(n),适用于需要判断两个字符串是否可以通过字符映射相互转换的场景。

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

Problem

Given two (dictionary) words as Strings, determine if they are isomorphic.

Two words are called isomorphic if the letters in one word can be remapped to get the second word.

Remapping a letter means replacing all occurrences of it with another letter while the ordering of the letters remains unchanged.

No two letters may map to the same letter, but a letter may map to itself.

 Example:

given "foo", "app"; returns true we can map f -> a and o->p
given "bar", "foo"; returns false we can't map both 'a' and 'r' to 'o'

given "ab", "ca"; returns true we can map 'a' -> 'b' and 'c' -> 'a'


最直接的方法就是见两个HashMap维护住字符的对应关系,O(n)


public static boolean check(String s,String t){
		if(s.length()!=t.length()) return false;
		HashMap<Character,Character> map1=new HashMap<Character, Character>();
		HashMap<Character,Character> map2=new HashMap<Character, Character>();
		
		for(int i=0;i<s.length();i++){
			char c1=s.charAt(i);
			char c2=t.charAt(i);
			if(map1.containsKey(c1)){
				if(map1.get(c1)!=c2) return false;
			}
			if(map2.containsKey(c2)){
				if(map2.get(c2)!=c1) return false;
			}
			
			map1.put(c1, c2);
			map2.put(c2, c1);
		}
		return true;
	}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值