95 判断两个字符串是否为变形词
Table of Contents

ac

给定两个字符串str1str2,如果str1str2中出现的字符种类出现的一样且每种字符出现的次数也一样,那么str1str2互为变形词。请判断str1str2是否为变形词。

时间复杂度`O(n)`,空间复杂度`O(n)`
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        int m = sc.nextInt();
        String s1 = sc.next();
        String s2 = sc.next();

        if (s1 == null || s2 == null || s1.length() != s2.length()) {
            System.out.println("false");
            return;
        }
        int[] charCnt1 = new int[256];
        int[] charCnt2 = new int[256];

        for(int i=0;i<s1.length();i++){
            charCnt1[s1.charAt(i)] ++;
        }
        for(int i=0;i<s2.length();i++){
            charCnt2[s2.charAt(i)] ++;
        }
        boolean flag = true;
        for(int i=0;i<256;i++){
            if(charCnt1[i] != charCnt2[i]){
                flag = false;
                break;
            }
        }
        if(!flag){
            System.out.println("false");
        }else {
            System.out.println("true");
        }
    }

}
/*
3 3
123
321

true

3 4
123
2331

false

4 3
1234
123

false
 */