Java 模式匹配器获取ArrayIndexOutOfBoundsException:0
下面是我试图做的伪代码:Java 模式匹配器获取ArrayIndexOutOfBoundsException:0,java,junit,pattern-matching,indexoutofboundsexception,Java,Junit,Pattern Matching,Indexoutofboundsexception,下面是我试图做的伪代码: procedure naive(T, P): result = { } for s = 0 to n – m match = true for j = 0 to m – 1 if T[s+j] ≠ P[j] match = false if match result = result + {s} 以下是我写的: public class naivepatternmatcher {
procedure naive(T, P):
result = { }
for s = 0 to n – m
match = true
for j = 0 to m – 1
if T[s+j] ≠ P[j]
match = false
if match
result = result + {s}
以下是我写的:
public class naivepatternmatcher {
public static Integer[] main(char[] T, char[] P) {
Integer[] results = {};
int count = 0;
boolean match;
for (int s = 0; s <= (T.length - P.length); s++) {
match = true;
for (int j = 0; j <= P.length - 1; j++) {
if (T[s + j] != P[j]) {
match = false;
}
}
if (match == true) {
results[count] = s;
count++;
}
}
return results;
}
}
有人能帮我解决这个问题并解释我遗漏了什么吗?您的
结果是一个固定大小为0的空数组,并且results[count]=s不会将数组的大小增加1并将s
的值附加到数组中。更好地使用这样一个动态增长的结果
另一个建议是,在内部for循环的if末尾添加对break
的调用,因为ifT[s+j]!=P[j]
无需进一步搜索模式的其余部分
if (T[s + j] != P[j]) {
match = false;
break
}
请参阅下面的代码,以获取保持returntype为Integer[]
且仅在内部使用ArrayList
的实现示例
public static Integer[] main(char[] T, char[] P) {
List<Integer> results = new ArrayList<>();
boolean match;
for (int s = 0; s <= (T.length - P.length); s++) {
match = true;
for (int j = 0; j <= P.length - 1; j++) {
if (T[s + j] != P[j]) {
match = false;
break;
}
}
if (match == true) {
results.add(s);
}
}
return results.toArray(new Integer[results.size()]);
}
publicstaticinteger[]main(char[]T,char[]P){
列表结果=新建ArrayList();
布尔匹配;
对于(int s=0;s或:Integer[]results={};
-->Integer[]results=new Integer[T.length-P.length];
public static Integer[] main(char[] T, char[] P) {
List<Integer> results = new ArrayList<>();
boolean match;
for (int s = 0; s <= (T.length - P.length); s++) {
match = true;
for (int j = 0; j <= P.length - 1; j++) {
if (T[s + j] != P[j]) {
match = false;
break;
}
}
if (match == true) {
results.add(s);
}
}
return results.toArray(new Integer[results.size()]);
}