字符串比较。暴力解决即可!!!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 题意:最少需要替换几个 A 中的字符,使得 A 为 B 的子串,然后输出替换的个数和位置
 * 
 * @author tinydolphin
 *
 */
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int strALength;
        int strBlength;
        int min;
        String strA;
        String strB;
        int count;
        int[] tempList;
        int[] list;
        while (in.hasNext()) {
            strALength = in.nextInt();
            strBlength = in.nextInt();
            strA = in.next();
            strB = in.next();
            // 初始化
            tempList = new int[strALength + 1];
            list = new int[strALength + 1];
            min = Integer.MAX_VALUE;
            // 整段比较,维护替换个数的最小值。
            for (int indexI = 0; indexI <= strBlength - strALength; indexI++) {
                count = 0;
                for (int indexJ = 0; indexJ < strALength; indexJ++) {
                    if (strA.charAt(indexJ) != strB.charAt(indexI + indexJ)) {
                        tempList[++count] = indexJ + 1;
                    }
                }
                if (count < min) {
                    min = count;
                    System.arraycopy(tempList, 1, list, 1, count);// 最优数组复制方式
                }
            }
            // 以下代码用作 输出结果
            out.println(min);
            for (int index = 1; index <= min; index++) {
                out.print(list[index]);
                out.print(index == min ? "\n" : " ");
            }
        }
        out.flush();
    }
}
Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐