leetcode205_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. 

题目大意

  给定两个字符串s和t,判断它们是否是同构的。如果字符串s可以通过字符替换的方式得到字符串t,则称s和t是同构的。字符的每一次出现都必须被其对应字符所替换,同时还需要保证原始顺序不发生改变。两个字符不能映射到同一个字符,但是字符可以映射到其本身。 

解题思路
  使用一个哈希表map维护两个字符串中字符的映射关系,同时用一个set保存映射的值。(s[i], t[i]),t[i].

出现的情况有5种:

1.s[i]与t[i]都没有出现过(用contains判断即可),那么在map和set中添加这一对元素

2.s[i]没有出现过,t[i]却在之前出现了,那么返回false

3.s[i]出现过,t[i]没有,那么返回false

4.s[i]与t[i]都出现过,但对应关系交叉了,比如egg与ada的第三对元素g与a,那么返回false

5.s[i]与t[i]都出现过,而且符合一一对应,这时是true

实现的代码中把3和4合成了一个判断:判断s[i]与t[i]是否满足之前储存的映射关系,如果t[i]不是s[i]映射元素,就返回false

class Solution {
    public boolean isIsomorphic(String s, String t) {
        // 两个字符串都为空
        if (s == null && t == null) {
            return true;
        }
        // 只有一个为空
        else if (s == null || t == null) {
            return false;
        }
        // 两个字符串的长度都为0(与空字符串不同,长度为0的串被分配了存储空间)
        else if (s.length() == 0 && t.length() == 0) {
            return true;
        }
        // 两个字符串的长度不相等
        else if (s.length() != t.length()) {
            return false;
        }

        // 保存映射关系 
        Map<Character, Character> map = new HashMap<>(s.length());
        Set<Character> set = new HashSet<>(t.length());

        char sChar;
        char tChar;
        for (int i = 0; i < s.length(); i++) {
            sChar = s.charAt(i);
            tChar = t.charAt(i);

            // 键未出现过,就保存映射关系
            if (!map.containsKey(sChar)) {
                if (set.contains(tChar)) {
                    return false;
                } else {
                    map.put(sChar, tChar);
                    set.add(tChar);

                }
            }
            // 如是键已经出现过
            else {

                // 原先的键映射的值是map.get(sChar),现在要映射的值是tChar
                // 如果两个值不相等,说明已经映射了两次,不符合,返回false

                if (map.get(sChar) != tChar) {
                    return false;
                }
            }
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值