1
我與運行時錯誤(NZEC)上SPOJ的問題所困擾, http://www.spoj.com/problems/NHAY/提交代碼是給運行時錯誤(NZEC)
我從我的身邊試過很多情況下,每次它是給在正確的輸出日食,但無法找出運行時錯誤的原因,同時提交此Spoj,任何人都可以請幫我解決這個錯誤。
這裏是我的代碼,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
class KMP {
public int[] lps(String needle, int needleLength)
{
int lps[] = new int[needleLength];
int j=0,i=1;
lps[0]=0;
while(i<needle.length())
{
if(needle.charAt(j) == needle.charAt(i))
{
lps[i] = j+1;
i++;
j++;
}
else
{
if(j != 0)
{
j = lps[j-1];
}
lps[i] = 0;
i++;
}
}
return lps;
}
public List<Integer> KMPalgo(String hayStack, String needle, int needleLengh)
{
int lps[] = lps(needle, needleLengh);
int i=0;
int j=0;
List<Integer> position = new ArrayList<Integer>();
while(i<hayStack.length())
{
if(hayStack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
if(j !=0)
{
j = lps[j-1];
}
else
i++;
}
if(needle.length() == j)
{
position.add(i-j);
if(j !=0)
j = lps[j-1];
}
}
return position;
}
public static void main(String[] args) throws NumberFormatException, IOException {
KMP o = new KMP();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String needlLength = bf.readLine().trim();
if(needlLength == null || needlLength.equals(""))
break;
int lNeedle = Integer.parseInt(needlLength);
String needle = bf.readLine().trim();
String haystack = bf.readLine().trim();
List<Integer> result= o.KMPalgo(haystack, needle, lNeedle);
System.out.println();
for(Integer itr : result)
System.out.println(itr);
}
}
}