g0201_0300.s0205_isomorphic_strings.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0201_0300.s0205_isomorphic_strings;
// #Easy #String #Hash_Table #Level_1_Day_2_String
// #2022_06_28_Time_2_ms_(99.97%)_Space_43.3_MB_(32.68%)
/**
* 205 - Isomorphic Strings\.
*
* Easy
*
* 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.
*
* **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
*
* **Constraints:**
*
* * 1 <= s.length <= 5 * 104
* * `t.length == s.length`
* * `s` and `t` consist of any valid ascii character.
**/
public class Solution {
public boolean isIsomorphic(String s, String t) {
int[] map = new int[128];
char[] str = s.toCharArray();
char[] tar = t.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
if (map[tar[i]] == 0) {
if (search(map, str[i], tar[i]) != -1) {
return false;
}
map[tar[i]] = str[i];
} else {
if (map[tar[i]] != str[i]) {
return false;
}
}
}
return true;
}
private int search(int[] map, int tar, int skip) {
for (int i = 0; i < 128; i++) {
if (i == skip) {
continue;
}
if (map[i] != 0 && map[i] == tar) {
return i;
}
}
return -1;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy