ZZULIOJ 1147: 查找子数组,Java

ZZULIOJ 1147: 查找子数组,Java

题目描述

给定两个整型数组,数组a有n个元素, 数组b有m个元素,1<=m<=n<100,请检验数组b是否是数组a的子数组。若从数组a的某个元素a[i]开始,有b[0]=a[i],b[1]=a[i+1],…,b[m]=a[i+m],则称数组b是数组a的子数组。

输入

输入第一行为两个整数n和m;第二行为数组a的n个整数;第三行为数组b的m个整数,各数据之间用空格隔开。

输出

输出占一行。若b是a的子数组,则输出子数组所在位置i,注意下标从0开始;否则输出No Answer

样例输入 Copy
8 3
3 2 6 7 8 3 2 5
3 2 5
样例输出 Copy
5
import java.io.*;

public class Main {
    
    
    public static void main(String[] args) throws IOException {
    
    
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] str = bf.readLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int m = Integer.parseInt(str[1]);
        int[] a = new int[n], b = new int[m];
        str = bf.readLine().split(" ");
        for (int i = 0; i < n; i++) {
    
    
            a[i] = Integer.parseInt(str[i]);
        }
        str = bf.readLine().split(" ");
        for (int i = 0; i < m; i++) {
    
    
            b[i] = Integer.parseInt(str[i]);
        }
        boolean ok = false;
        for (int i = 0; i < n - m + 1; i++) {
    
    
            int j;
            for (j = 0; j < m; j++) {
    
    
                if (a[i + j] != b[j]) {
    
    
                    break;
                }
            }
            if (j == m) {
    
    
                ok = true;
                bw.write(i + "\n");
                break;
            }
        }
        if (!ok) bw.write("No Answer\n");
        bw.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_52792570/article/details/132567018