ISOMORPHIC STRINGS
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.
import java.util.*;
public class Hello {
public static void main(String[] args) {
HashMap<Character,Character> hs=new LinkedHashMap<Character,Character>();
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
if(s1==null&&s2==null)
{
System.out.println("YES");
return;
}
int n=s1.length();
int n1=s2.length();
if(n!=n1)
{
System.out.println("NO");
return;
}
for(int i=0;i<n;i++)
{char c1=s1.charAt(i);
char c2=s2.charAt(i);
if(hs.containsKey(c1))
{
if(hs.get(c1)!=c2)
{
System.out.println("NO");
return;
}
}
else{
if(hs.containsValue(c2))
{
System.out.println("NO");
return;
}hs.put(c1,c2);
}}
System.out.println("YES");
}
}
No comments:
Post a Comment