LeetCode中的Isomorphic Strings 的java实现

来源:互联网 发布:在线报名系统 php 编辑:程序博客网 时间:2024/06/02 10:38

题目是全英文的,不过都是简单的英文,一般都可以完全看懂,题目如下:

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;
    }
}

0 0
原创粉丝点击