目录

2025年-H128-Lc205.-同构字符串哈希表-Java版

2025年- H128-Lc205. 同构字符串(哈希表)–Java版

1.题目

https://i-blog.csdnimg.cn/direct/7f8b898fc6434827be7e8e2d235435a6.png

2.思路

不要在循环中直接 return true

只在遍历完整个字符串之后,没有发现冲突时返回 true

把映射关系放入map中

3.代码实现

class Solution {
    public boolean isIsomorphic(String s, String t) {
        
        //保存映射关系
        Map<Character,Character> m1=new HashMap<Character, Character>();
        Map<Character,Character> m2=new HashMap<Character, Character>();
        int n=s.length();
        int n2=t.length();
        if(n!=n2)
        {
            return false;
        }
        for(int i=0;i<n;i++)
        {
          char x=s.charAt(i);
          char y=t.charAt(i);
          if(m1.containsKey(x)&&m1.get(x)!=y||(m2.containsKey(y)&&m2.get(y)!=x)) 
          {
            return false;
          }
          //否则就是true的情况
          m1.put(x,y);
          m2.put(y,x);
         
        }
        return true;

        
    }
}