ZZULIOJ 1147: Finding subarrays, Java
Question description
Given two integer arrays, array a has n elements, array b has m elements, 1<=m<=n<100, please check whether array b is a subarray of array a. If starting from an element a[i] of array a, there are b[0]=a[i], b[1]=a[i+1],…, b[m]=a[i+m] , then array b is said to be a subarray of array a.
enter
The first line of input is two integers n and m; the second line is the n integers of array a; the third line is m integers of array b, with spaces separating each data.
output
The output occupies one line. If b is a subarray of a, output the position i of the subarray. Note that the subscript starts from 0; otherwise, output No Answer
.
Sample inputCopy
8 3
3 2 6 7 8 3 2 5
3 2 5
Sample outputCopy
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();
}
}