访问数组元素时发生Java字符串越界异常
public class App {
public static int min(int x, int y)
{
if(x<y)
return x;
else
return y;
}
public static int minPalPartition(String str)
{
int n = str.length();
boolean P[][] = new boolean[n][n];
int DP[][] = new int[n][n];
//for all the string with start index and end index is same that is length is 1, string is palindrome and cut needed is 0
for(int i=0; i<n; i++)
{
P[i][i] = true;
DP[i][i] = 0;
}
/*
* i start index
* j end index
* k intermediate index
* l length
*/
int i, j, k, l;
for(l=2; l<=n; l++)
{
for(i=0; i<n-1; i++) //as starting index start at 0 it can go till n-2, n=3, i =0, j=1 and i=1, j=2 is the combination
{
j=i+l-1;
/* first determine P[i][j], if P[i][j] is true then DP[i][j] is 0
* if only 2 letter just check first and last letter
* otherwise last 2 letter and previous result
*/
if(l==2)
{
P[i][j] = (str.charAt(i) == str.charAt(j));
}
else
{
P[i][j] = (str.charAt(i)== str.charAt(j)) && P[i+1][j-1];
}
if(P[i][j] == true)
{
DP[i][j] = 0;
}
else
{
DP[i][j] = Integer.MAX_VALUE;
for(k=i; k<j; k++)
{
DP[i][j] = min(DP[i][j], (DP[i][k] + DP[k+1][j] + 1));
}
}
}
}
return DP[0][n-1];
}
public static void main(String[] args) {
String str = "ababbbabbababa";
System.out.println("length of the string " + str.length());
System.out.println("pal partition Need for [" + str + "] : " + minPalPartition(str));
}
}
在上面的代码中,我得到了下面的异常
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
at java.lang.String.charAt(String.java:658)
at Client.App.minPalPartition(App.java:54)
at Client.App.main(App.java:79)
基本上,它在这一行给出了例外
P[i][j] = (str.charAt(i)== str.charAt(j)) && P[i+1][j-1];
有什么问题?如何避免
这是一个字符串的回文分区问题
# 1 楼答案
正如其他人在评论中已经提到的,您在以下代码行中遇到了问题
因此,您的编码在
l = 3
和i = 12
时引发异常,因为j
然后变成12 + 3 - 1 = 14
。由于字符串长度为14,因此无法访问索引14,因此会出现StringIndexOutOfBoundsException
异常根据您在代码中的注释,我猜您需要的是:
注意内部循环的条件,它的
i < n - l
,而不是i < n - 1
。因此,j
的最大值可以是:我不知道你想用你的代码做什么,但我在阅读了你在代码中的评论后根据我的猜测提出了这个建议
# 2 楼答案