mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 01:35:16 +08:00
Add Isomorphic Strings (#3253)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
This commit is contained in:
33
src/main/java/com/thealgorithms/strings/Isomorphic.java
Normal file
33
src/main/java/com/thealgorithms/strings/Isomorphic.java
Normal file
@ -0,0 +1,33 @@
|
||||
package com.thealgorithms.strings;
|
||||
import java.util.*;
|
||||
|
||||
public class Isomorphic {
|
||||
public static boolean checkStrings(String s, String t) {
|
||||
if(s.length() != t.length()){
|
||||
return false;
|
||||
}
|
||||
|
||||
// To mark the characters of string using MAP
|
||||
// character of first string as KEY and another as VALUE
|
||||
// now check occurence by keeping the track with SET data structure
|
||||
Map<Character, Character> characterMap = new HashMap<Character, Character>();
|
||||
Set<Character> trackUinqueCharacter = new HashSet<Character>();
|
||||
|
||||
for(int i=0; i<s.length(); i++){
|
||||
if(characterMap.containsKey(s.charAt(i))){
|
||||
if(t.charAt(i) != characterMap.get(s.charAt(i))){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(trackUinqueCharacter.contains(t.charAt(i))){
|
||||
return false;
|
||||
}
|
||||
|
||||
characterMap.put(s.charAt(i), t.charAt(i));
|
||||
}
|
||||
trackUinqueCharacter.add(t.charAt(i));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user