205. Isomorphic Strings 🔍
Difficulty: Easy - Tags: Hash Table, String
Problem Statement 📜
Given two strings s and t, determine 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.
Examples 🌟
🔹 Example 1:
Input:
s = "egg", t = "add"Output:
true🔹 Example 2:
Input:
Output:
🔹 Example 3:
Input:
Output:
Constraints ⚙️
1 <= s.length <= 5 * 10^4t.length == s.lengthsandtconsist of any valid ASCII character.
Solution 💡
To determine if two strings are isomorphic, we need to map characters from s to t while ensuring no two characters from s map to the same character in t (and vice versa).
Java Solution
Explanation of the Solution
Create Two Maps:
sToTto map characters fromstot.tToSto map characters fromttos.
Iterate Through Both Strings:
For each character in
sandt:Check if the mappings are consistent in both directions.
If not, return
false.
Result:
If all character mappings are consistent, return
true.
Time Complexity ⏳
O(n):
nis the length of the strings.Each character is visited once.
Space Complexity 💾
O(1):
Fixed space for the hash maps since the character set is limited (ASCII).
You can find the full solution here.
Last updated
Was this helpful?