您的位置:首页 > 其它

[leetcode]205. Isomorphic Strings

2017-03-29 23:51 330 查看
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.

用两个hashmap保存两个String的字符及其在原字符串中的位置,当遇到相同字符时,比较两个字符在原字符串的位置,不相等则返回false

public class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character,Integer> s_map=new HashMap<>();
HashMap<Character,Integer> t_map=new HashMap<>();
if(s.equals(t)){
return true;
}
if(s.length()==1){
return false;
}
for(int i=0;i<s.length();i++){
if(s_map.containsKey(s.charAt(i))&&!t_map.containsKey(t.charAt(i))
||!s_map.containsKey(s.charAt(i))&&t_map.containsKey(t.charAt(i))){
return false;
}
else if(s_map.containsKey(s.charAt(i))&&t_map.containsKey(t.charAt(i))){
if(s_map.get(s.charAt(i))!=t_map.get(t.charAt(i))){
return false;
}
}
else{
s_map.put(s.charAt(i),i);
t_map.put(t.charAt(i),i);
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: