当前位置:网站首页>Leecode-205. 同构字符串
Leecode-205. 同构字符串
2022-08-09 23:26:00 【风吟Pro】
主要思路就是用哈希Map以K-V的形式来进行两个字符串同一个位置上的格式映射
leetcode官方思路
我们维护两张哈希表,
第一张哈希表s2t 以 s 的字符为键,映射至 t 的字符为值,
第二张哈希表t2s 以 t 的字符为键,映射至 s 的字符为值。
从左至右遍历两个字符串的字符,不断更新两张哈希表
如果出现冲突
(即当前下标 index 对应的字符 s[index] 已经存在映射且不为 t[index] 或当前下标 index 对应的字符 t[index] 已经存在映射且不为 s[index])时说明两个字符串无法构成同构,返回 false。
如果遍历结束没有出现冲突,则表明两个字符串是同构的,返回 true 即可。
class Solution {
public boolean isIsomorphic(String s, String t) {
//创建哈希表
Map<Character, Character> s2t = new HashMap<Character, Character>();
Map<Character, Character> t2s = new HashMap<Character, Character>();
//这里不用管遍历多少遍,如果遍历都不不够长,那么必然是字符串长度不同,也就是不同构
for(int i=0;i<s.length();++i){
//拿到每个位置的字符
char x=s.charAt(i);
char y=t.charAt(i);
//如果任意一个表的key已经存在,并且拿到的value和当前的目标value不一致,就代表映射失败
if(s2t.containsKey(x)&&s2t.get(x)!=y||
t2s.containsKey(y)&&t2s.get(y)!=x){
return false;
}
//匹配成功,把当前的映射存进两个表
s2t.put(x,y);
t2s.put(y,x);
}
return true;
}
}
边栏推荐
猜你喜欢
LSTM-based distributed energy generation prediction (Matlab code implementation)
数字孪生电力系统,可视化应用实现科学调度的电子设备
YOLOV5 study notes (7) - training your own data set
CST Studio Suite 2021软件安装包和安装教程
781. 森林中的兔子
【SSL集训DAY2】Sort【树状数组】
WPF DataGrid using data templates
In-depth understanding of multithreading (Part 1)
字节技术面都过了,薪资都谈好了20K*13结果还是被刷了,问HR原因是。。。
巴比特 | 元宇宙每日必读:国内首个数字人产业专项支持政策发布,2025年北京数字人产业规模将破500亿元...
随机推荐
Travel with Shengteng: See all the AI attractions in Jinling City in one day
go语言的并发原理(goroutine)
Copper's emotion
【JZOF】77 Print binary tree in zigzag
redis distributed lock code example
NotWritableError: The current user does not have write permissions when conda creates a new environment
什么是服务治理
【集训DAY5】选数字【数学】
GoLang 使用 goroutine 停止的几种办法
New window Display Agreement
Redis-基本介绍/linux下环境配置/配置文件
考柏的感慨
E - Sugoroku 3(期望dp)
关于服务治理
分布式数据库难题(二):数据复制
数据库优化 | 干货
conda新建环境时报错NotWritableError: The current user does not have write permissions
When knowledge and action are one
Cmake 用法记录
二进制、八进制、十进制、十六进制之间的转换