我有一个关于String 3中codingbat问题的问题。问题如下:
Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string. In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping).
例如,字符串“abXYZba”的镜像结尾为“ab”
mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"
我的代码如下:
public String mirrorEnds(String string) {
if(string.length() <=1) return string;
String x = "";
int y = string.length() - 1;
for(int i = 0; i < string.length()/2; i++)
{
if(string.charAt(i) == string.charAt(y))
{
x+= Character.toString(x.charAt(i));
y--;
}
else
{
return x;
}
}
return string;
}
当我尝试执行以下操作时:
"xxYxx"
字符串长度为 5,因此索引为 0-4。如果我在我的代码上运行它,逻辑将是:
i = 0 and y = 4;
string.charAt(i) == string.charAt(y) //true and i++ and y--
string.charAt(i) == string.charAt(y) //true and i++ and y--
//i is == string.length()/2 at this point
但是这个问题向我抛出了一个错误,指出indexoutofbounds。为什么会这样?
最佳答案
您正在访问错误字符串的第 i
个字符:
x += Character.toString(x.charAt(i));
字符串x
一开始是空的,因此索引0处的字符不存在。
改为访问原始字符串
。
x += Character.toString(string.charAt(i));
关于Java字符串索引在for循环中越界(codingbat函数mirrorEnds),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038868/