Isomorphic Strings LeetCode (Check if two strings are isomorphic)

Given two strings s and tdetermine if they are isomorphic.

Two strings s and t 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.

 Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

NOTE:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s and t consist of any valid ascii character.
This problem is popular in LeetCode, GeeksForGeeks, and StackOverFlow A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions
Solution:
import java.util.*;

public class IsomorphicStrings{
//assuming both strings are of same length, check the number of unique chars in both string
//check ordering by having an array to store 512 characters, 256 from each of the given input strings
public static boolean isomorph(String s, String t){
int[] chars = new int[512];
for(int i=0;i<s.length(); i++){
//ensures that the previously mapped position of chars is retained in future comparisons
if(chars[s.charAt(i)]!=chars[t.charAt(i) + 256]){
return false;
}
chars[s.charAt(i)] = chars[t.charAt(i) + 256] = i+1;
}
return true;
}

public static void main(String[] args){
System.out.println(isomorph("egg", "add"));//true
System.out.println(isomorph("foo", "bar"));//false
System.out.println(isomorph("paper", "title"));//true
System.out.println(isomorph("aba", "baa"));//should be false
}
}

No comments:

Post a Comment