您的位置:首页 > 其它

Isomorphic Strings

2015-05-29 10:04 387 查看
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.

思路:用一个hash表来存储两个字符串中字符的映射关系,当出现的字符已经在hash表中出现过,但映射关系与在hash表中原有的映射关系不同时,说明字符串不是同构的,但是也要注意万一出现两个字符映射到同一个字符,比如“ab” 和“aa” 中a和b映射同时映射到a,先把<a,a>放入hash表中,当遍历到b字符的时候,先判断hash表中有没有出现key为b的情况,很显然还没出现过,然后再判断hash表中value有没有出现过a,如果出现了说明已经有字符映射到a了,此时出现某个字符和b映射到同一个字符的情况,说明两个字符串不是同构的。

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