Isomorphic Strings
2016-05-29 17:14
309 查看
题目描述:
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
Given
Given
题目很简单,稍微注意一点:
这里s,t要相互比较才行,不然仅仅是isomorphic(s,t)的话,"ab","aa"也满足,事实是不符合题意的。
代码如下:
public class Solution {
public boolean isomorphic(String s, String t) {
Map<Character, Character> map=new HashMap<Character, Character>();
for(int i=0;i<s.length();i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i), t.charAt(i));
}else{
if(t.charAt(i)!=map.get(s.charAt(i)))
return false;
}
}
return true;
}
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length())
return false;
return isomorphic(s, t)&& isomorphic(t, s);
}
}
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.
题目很简单,稍微注意一点:
这里s,t要相互比较才行,不然仅仅是isomorphic(s,t)的话,"ab","aa"也满足,事实是不符合题意的。
代码如下:
public class Solution {
public boolean isomorphic(String s, String t) {
Map<Character, Character> map=new HashMap<Character, Character>();
for(int i=0;i<s.length();i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i), t.charAt(i));
}else{
if(t.charAt(i)!=map.get(s.charAt(i)))
return false;
}
}
return true;
}
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length())
return false;
return isomorphic(s, t)&& isomorphic(t, s);
}
}
相关文章推荐
- CentOS,Ubuntu,Gentoo,Freebsd,RedHat,Debian的区别及选择
- 修改内核临时端口范围
- eclipse中遇到的快捷键问题
- C++ map 中的reverse_iterator
- 同步代码块什么时候释放锁
- MTSimpleAdapter框架扩展——添加empty页面、error页面和loading等特性
- 内外网同时上网的方法
- MAC OS下JDK版本切换指南
- MAC OS下JDK版本切换指南
- MAC OS下JDK版本切换指南
- Duilib学习总结
- 第二次冲刺个人工作总结05
- OpenGL学习脚印: 模型变换(model transformation)
- Linux 常用命令积累
- 修改代码
- [c++] vector的使用
- gcd
- websocket服务端PHP代码
- 二叉树前序,中序,后序求法
- POJ 2286 The Rotation Game IDA*