Isomorphic Strings
2015-11-12 13:31
225 查看
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
return true.
Given
return false.
Given
return true.
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s == null || t == null)
return false;
if(s.length() == 0 && t.length() == 0)
return true;
if(s.length() != t.length())
return false;
Map<Character, Character> map = new HashMap<>();
Set<Character> set = new HashSet<>();
for(int i = 0; i < s.length(); i++){
Character sChar = s.charAt(i);
Character tChar = t.charAt(i);
if(!map.containsKey(sChar)){
if(!set.contains(tChar)){
set.add(tChar);
map.put(sChar, tChar);
}
else
return false;
}
else{
Character mappedValue = map.get(sChar);
if(!mappedValue.equals(tChar))
return false;
}
}
return true;
}
}
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.
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s == null || t == null)
return false;
if(s.length() == 0 && t.length() == 0)
return true;
if(s.length() != t.length())
return false;
Map<Character, Character> map = new HashMap<>();
Set<Character> set = new HashSet<>();
for(int i = 0; i < s.length(); i++){
Character sChar = s.charAt(i);
Character tChar = t.charAt(i);
if(!map.containsKey(sChar)){
if(!set.contains(tChar)){
set.add(tChar);
map.put(sChar, tChar);
}
else
return false;
}
else{
Character mappedValue = map.get(sChar);
if(!mappedValue.equals(tChar))
return false;
}
}
return true;
}
}
相关文章推荐
- 关于开发人员申请苹果账号相关事宜
- Robotframework+ride中test template的用法
- Unix学习笔记-----编程练习实例------使用vfork&&execv()在程序中加载可执行程序
- 距离
- 大神文章系列链接
- BFS DFS
- win7 64编译64位boost
- IOS Iphone 6 以及Iphone6 Plus 屏幕的适配
- TestField设置长度
- LeetCode(129) Sum Root to Leaf Numbers
- android某加固脱壳(一)
- LeetCode(129) Sum Root to Leaf Numbers
- 平台顺利通过公安部一所《GBT 28181-2011 安全防范视频监控联网系统信息传输、交换、控制技术要求》检测
- Bozosort: Sorting by Exchanging
- 一句shell命令搞定代码行数统计
- soj 3014: Seek the Name, Seek the Fame (字符串hash)
- Ubuntu下自己编译安装和卸载软件
- Theaon:theaon的图结构
- spring+hibernate工程使用JNDI连接部署至websphere,报错Caused by: java.lang.ClassNotFoundException: oracle.sql.BLO
- Robot FrameworkResource及关键字的使用