Created
March 11, 2016 13:44
-
-
Save humayun0156/25a32e363056b43a91bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* @author humayun | |
* http://www.programcreek.com/2014/05/leetcode-isomorphic-strings-java/ | |
* https://leetcode.com/problems/isomorphic-strings/ | |
* "egg" & "add" -> true [(e,a), (g,d), (g,d)] | |
* "foo" & "bar" -> false [(f,b), (o,a), (o,r)] | |
*/ | |
public class IsomorphicWord { | |
public static void main(String[] args) { | |
System.out.println(new IsomorphicWord().isIsomorphic("paper", "title")); | |
} | |
public boolean isIsomorphic(String s, String t) { | |
if (s == null || t == null) { | |
return false; | |
} | |
if (s.length() != t.length()) { | |
return false; | |
} | |
if (s.length() == 0 && t.length() == 0) { | |
return true; | |
} | |
Map<Character, Character> map = new HashMap<>(); | |
for (int i = 0; i < s.length(); i++) { | |
Character c1 = s.charAt(i); | |
Character c2 = t.charAt(i); | |
Character c = getKey(map, c2); | |
if (c != null & c != c1) { | |
return false; | |
} else if (map.containsKey(c1)) { | |
if (c2 != map.get(c1)) { | |
return false; | |
} | |
} else { | |
map.put(c1, c2); | |
} | |
} | |
return true; | |
} | |
private Character getKey(Map<Character, Character> map, Character target) { | |
for (Map.Entry<Character, Character> entry : map.entrySet()) { | |
if (entry.getValue().equals(target)) { | |
return entry.getKey(); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment