LeetCode-Isomorphic Strings

直接的方法就是想到了用两个hashmap 记录每个的id,即第几个出现的unique字母,再出现这个字母的时候 它的id就去map里面查看

出现新的字母 id ++

然后判断此时这两个string的对应字母的id是否一致

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if ( s == null || t == null )
            return true;
        int length = s.length();
        HashMap<Character,Integer>sset = new HashMap<Character,Integer>();
        HashMap<Character,Integer>tset = new HashMap<Character,Integer>();
        int counts = 0;
        int countt = 0;
        int curS = counts;
        int curT = countt;
        for ( int i = 0; i < length; i ++ ){
            if ( !sset.containsKey(s.charAt(i)) ){
                counts ++;
                sset.put( s.charAt(i), counts );
            }
            curS = sset.get(s.charAt(i));
            if ( !tset.containsKey(t.charAt(i)) ){
                countt ++;
                tset.put( t.charAt(i), countt);
            }
            curT = tset.get(t.charAt(i));
            if ( curS != curT )
                return false;
        }
        return true;
    }
}

看了答案发现简便算法:

只用记录每个字母出现的最后位置 然后每遇到一个字母 就对比此位置是否一样 用了两个256数组

注意!!!因为数组初始化成了0 所以为了和还没有遇到过这个字母区别开,每次fuzhi要加1

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        int [] sArr = new int [ 256 ];
        int [] tArr = new int [ 256 ];
        for ( int i = 0; i < s.length(); i ++ ) {
            if ( sArr[s.charAt(i)] != tArr[t.charAt(i)] )
                return false;
            sArr[s.charAt(i)] = i + 1;
            tArr[t.charAt(i)] = i + 1;
        }
        return true;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值