Isomorphic Strings
Input: s = "egg", t = "add"
Output: trueInput: s = "foo", t = "bar"
Output: falseInput: s = "paper", t = "title"
Output: trueclass Solution {
public boolean isIsomorphic(String s, String t) {
// put all chars from s and t into a map that contains char and number of occurances
// then compare the maps sizes, if the are they same, it is isomorphic, otherwise false
Map<Character, Integer> sMap = createMap(s);
Map<Character, Integer> tMap = createMap(t);
return sMap.size() == tMap.size();
}
private Map<Character, Integer> createMap(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char key = s.charAt(i);
if (map.containsKey(key)) {
Integer value = map.get(key);
map.put(key, value + 1);
} else {
map.put(key, 1);
}
}
return map;
}
}Last updated