面试题 01.02. 判定是否互为字符重排
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例 1:

输入: s1 = "abc", s2 = "bca"
输出: true
示例 2:

输入: s1 = "abc", s2 = "bad"
输出: false
说明:

0 <= len(s1) <= 100
0 <= len(s2) <= 100

题解:
字符串词频统计
IMG_20220927_173543

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        int n = s1.length(), m = s2.length(), tot = 0;
        if (n != m) return false;
        int[] cnts = new int[256];
        for (int i = 0; i < n; i++) {
            if (++cnts[s1.charAt(i)] == 1) tot++;
            if (--cnts[s2.charAt(i)] == 0) tot--;
        }
        return tot == 0;
    }
}

每次的词频都会统计在cnts中,tot是为了统计词频是否相同,只有词频相同时tot才为0;
太秒了,妙蛙种子!

Last modification:September 27th, 2022 at 05:41 pm
如果觉得我的文章对你有用,请随意赞赏