本文主要是介绍LeetCode中的Isomorphic Strings 的java实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目是全英文的,不过都是简单的英文,一般都可以完全看懂,题目如下:
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
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;
}
}
这篇关于LeetCode中的Isomorphic Strings 的java实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!