字符串同构问题——leetcode205/leetcode290

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

相同的题目:
对于仅由小写字母组成的字符串A和字符串B,如果分别存在一个小写字母由a到z的排列,使得将A中所有字母a替换为排列的第一个字母,所有字母B替换为第二个字母,所有字母z替换为排列的最后一个字母之后,A和B完全相同。那么称字符串A和字符串B相似,如abcc和xyaa。现在给定长度不超过10**5的字符串S和T,求S中有多少子串与T相似?

public class Main {

static int solve(String S, String T) {
    int lenS = S.length();
    int lenT = T.length();
    int count = 0;
    if (lenS < lenT) {
        for (int i = 0; i <= lenT - lenS; i++) {
            if (isIsomorphic((String) T.subSequence(i, i + lenS), S)) {
                count++;
            }
        }
    } else {
        for (int i = 0; i <= lenS - lenT; i++) {
            if (isIsomorphic((String) S.subSequence(i, i + lenT), T)) {
                count++;
            }
        }
    }
    return count;
}

public static boolean isIsomorphic(String s, String t) {
    if (s == null || t == null) {

        return false;
    }
    HashMap<Character, Character> hashMap = new HashMap<Character, Character>();
    for (int i = 0; i < s.length(); i++) {
        char c1 = s.charAt(i);
        char c2 = t.charAt(i);
        if (hashMap.containsKey(c1)) {
            if (hashMap.get(c1) == c2) {
                continue;
            } else {
                return false;
            }
        } else {
            if (hashMap.containsValue(c2)) {
                return false;
            } else {
                hashMap.put(c1, c2);
            }
        }
    }
    return true;
}



public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int res;

    String _S;
    try {
        _S = in.nextLine();
    } catch (Exception e) {
        _S = null;
    }

    String _T;
    try {
        _T = in.nextLine();
    } catch (Exception e) {
        _T = null;
    }

    res = solve(_S, _T);
    System.out.println(String.valueOf(res));

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值