205. Isomorphic Strings
来源:互联网 发布:浙江旅游数据 编辑:程序博客网 时间:2024/05/20 15:12
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.
问题:判断两个字符串是否同构,假定字符串长度相等
思想:(1)借助map<a1,a2>,字符串s和t,相当于两个映射,从s1->s2和从s2->s1的,比如egh和add, ea是一对 gd是一对 但是hd又是一对,此刻不满足: 但是map比较耗时
如果map.contains(a1)且map.get(a1)!=a2,则映射不成立
如果map里没有a1,但是有值a2表明先gd又来hd这种情况。
public boolean isIsomorphic(String s, String t) {//利用map if(s==null&&t==null||s.length()==0&&t.length()==0) return true; if(s==null||t==null||s.length()!=t.length()) return false; Map<Character,Character> map=new HashMap(); map.put(s.charAt(0), t.charAt(0)); for(int i=1;i<s.length();i++){ char a1=s.charAt(i); char a2=t.charAt(i); if(map.containsKey(a1)){ if(map.get(a1)!=a2) return false; }else if(map.containsValue(a2)){ return false; } else{ map.put(a1, a2); } } return true; }(2)高效的办法--数组,只应用于ASCII码
数组:字符a1 a2在两个字符串s1 s2中最后出现的位置,如果之前的存储位置不同,那么很显然两者是不同构的
public boolean isIsomorphic2(String s,String t){ int[] pos=new int[512]; for(int i=0;i<s.length();i++){ if(pos[s.charAt(i)]!=pos[t.charAt(i)+256]) return false; pos[s.charAt(i)]=i+1;//因为pos初始化时全是0,如果=i的话, //两个字符串首个字符同构存的值是0,和没出现没差,所以=i+1 pos[t.charAt(i)+256]=i+1; } return true; }
0 0
- 205. Isomorphic Strings
- 【LeetCode】205.Isomorphic Strings
- [leetcode] 205.Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings LeetCode
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 【LeetCode】205. Isomorphic Strings
- LeetCode *** 205. Isomorphic Strings
- leetcode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- Ubuntu下GDAL读取HDF4(MODIS影像)开发环境搭建
- Android studio快速获取获取Android SHA1与MD5
- configure: error: xml2-config not found. Please check your libxml2 installation
- CentOS7.3部署OpenStack-Ocata版本手记(控制节点)
- 关于CodeBlock在调试时断点处不停的解决方法
- 205. Isomorphic Strings
- Stereo Matching文献笔记之(二):《A Non-Local Cost Aggregation Method for Stereo Matching》读后感~
- Java重建二叉树
- 关于pair容器的用法
- eclipse 高占用内存
- logback配置文件解析
- 第七讲——【项目1-k次方之和】
- ACM习题Y-25
- swift 简单易用类似新闻客户端的结构