public boolean contains(int[] a,int[] b) {
int w=0;
for(int i=0;i<a.length && w<b.length;i++) {
if(a[i]==b[w])
w++;
else w=0;
}
System.out.println(w);
if(w==b.length) return true;
else return false;
}
由于显而易见的原因,此代码对于scenario-contains({1,2,1,2,3},{1,2,3})失败。但是,我无法在正确的输出中添加正确的代码。请帮帮我。
答案 0 :(得分:0)
试试这个
public static boolean contains(int[] a,int[] b) {
String s1= Arrays.toString(a).replaceAll("\\[|\\]","");
String s2= Arrays.toString(b).replaceAll("\\[|\\]","");
if(s1.contains(s2)){
return true;
} else {
return false;
}
}
直播Demo
代码中的问题
for(int i=0;i<a.length && w<b.length;i++) {//a={1, 2, 1, 2, 3},b= {1, 2, 3}
if(a[i]==b[w])// first two element are same in both arrays
w++;// then w=2, but a[2] !=b[2].
else w=0;// So w=0, but in next round it will check
//equality as a[3]==b[0] that's false.
}