跪求各位大佬解答,当测试用例为""时,在LeetCode中result = s.charAt(0) + “”;一行提示下标越界,但在IDEA和eclipse中都能正常运行???
class Solution {
public String findSubstring(int i, int j, String s){
do{
j++;
i--;
}while(i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j));
return s.substring(i + 1, j);
}
public String longestPalindrome(String s) {
int i = -1;
String sub = "", result = "";
Set<String> set = new HashSet<>();
int length = 0;
for(i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i + 1)){
set.add(findSubstring(i, i + 1, s));
}
if(i + 2 < s.length() && s.charAt(i) == s.charAt(i + 2)){
set.add(findSubstring(i, i + 2, s));
}
}
if(s == ""||s == null) result = "";
else if(set.isEmpty()) {
result = s.charAt(0) + "";
//result = s.toCharArray()[0] + "";
}
else{
Iterator<String> it = set.iterator();
while(it.hasNext()){
sub = it.next();
if (sub.length() >= length) {
result = sub;
length = sub.length();
}
}
}
return result;
}
}
经过反复尝试,发现在else if(set.isEmpty()) 中再加入&&s.length()>0就可以了,不过讲道理“”这种情况根本进不到这个里面吧,反正idea和eclipse都完美运行。。。
担心是编译时检查的问题,为此特意编写以下代码在idea中运行,结果是1,我真是佛了。
if(1==1)
System.out.println("1");
else if (2==2)
System.out.println("2");