您的位置:首页 > 编程语言 > Java开发

LeetCode中的Isomorphic Strings 的java实现

2015-05-22 10:32 363 查看
题目是全英文的,不过都是简单的英文,一般都可以完全看懂,题目如下:

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
自己用java写的实现,如下:
public class Solution {

    public boolean isIsomorphic(String s, String t) {

        HashMap<Character, Character> ht = new HashMap<Character,Character>();
HashMap<Character, Character> hs = new HashMap<Character,Character>();
char[] sArray = s.toCharArray();
char[] tArray = t.toCharArray();
for(int i=0;i<s.length();i++)
{
for(char s1: ht.keySet())
{
if(sArray[i]==s1&&ht.get(s1)!=tArray[i])
{
return false;
}
}
ht.put(sArray[i], tArray[i]);

}
for(int i=0;i<t.length();i++)
{
for(char t1:hs.keySet())
{
if(tArray[i]==t1&&hs.get(t1)!=sArray[i])
{
return false;
}
}
hs.put(tArray[i], sArray[i]);
}
return true;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode