[Leetcode] 205. Isomorphic Strings

  1. Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.
Two strings 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.
For example,Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:You may assume both s and t have the same length.

Subscribe to see which companies asked this question

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Set usedSet = new HashSet<>();
        Map charMap = new HashMap<>();
        for(int i = 0; i < s.length(); i++){
            Character ch = charMap.get(s.charAt(i));
            Character si = s.charAt(i);
            Character ti = t.charAt(i);
            if(ch == null){
                if(usedSet.contains(ti) == false){
                    charMap.put(si, ti);
                    usedSet.add(ti);
                }
                else return false;
            }
            else{
                if(ch != ti) return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:([Leetcode] 205. Isomorphic Strings)