英文:
Why do I get a StringOutOfBoundsException even though I am within bounds of the String array?
问题
class Solution {
public boolean isPalindrome(String s) {
if (s == null) {
throw new IllegalArgumentException("Illegal input!");
}
if (s.length() <= 1) {
return true;
}
int startPtr = 0;
int endPtr = s.length() - 1;
while (startPtr < endPtr) {
while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(startPtr))) {
startPtr++;
}
//ERROR while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(endPtr))) {
//endPtr--;
//}
if (startPtr < endPtr && Character.toLowerCase(s.charAt(startPtr)) != Character.toLowerCase(s.charAt(endPtr))) {
return false;
}
startPtr++;
endPtr++; // Note: It should be "endPtr--" instead of "endPtr++"
}
return true;
}
}
英文:
I'm currently attempting this problem and seem to keep getting this StringOutOfBoundsException
, can anyone explain to me why?
When I exit the while loop, it seems that I mistyped endPtr--;
class Solution {
public boolean isPalindrome(String s) {
if (s == null) {
throw new IllegalArgumentException("Illegal input!");
}
if (s.length() <= 1) {
return true;
}
int startPtr = 0;
int endPtr = s.length() - 1;
while (startPtr < endPtr) {
while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(startPtr))) {
startPtr++;
}
//ERROR while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(endPtr))) {
//endPtr--;
//}
if (startPtr < endPtr && Character.toLowerCase(s.charAt(startPtr)) != Character.toLowerCase(s.charAt(endPtr))) {
return false;
}
startPtr++;
endPtr++;
}
return true;
}
}
答案1
得分: 1
在主循环的最后,你正在增加 endPtr。
startPtr++;
endPtr++;
通过这样做,你将字符串的结尾位置放在了实际结尾之后。
错误随之而来。
此外,你正在创建一个无限循环,因为条件
while (startPtr < endPtr)
将始终为真。
英文:
In the end of the main loop, you are incrementing endPtr.
startPtr++;
endPtr++;
By doing so, you are positionning the end of your String after its real ending.
And here comes the error.
And also, you are creating an infinite loop because the condition
while (startPtr < endPtr)
will always be true.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论