【发布时间】:2019-03-12 12:21:52
【问题描述】:
我试图在 Leetcode 中解决 question,讨论的解决方案之一如下:
public class Solve {
public static void main(String[] args) {
String haystack = "mississippi";
String needle = "issip";
System.out.println(strStr(haystack,needle)) ;
}
public static int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
}
编译器不应该在这里抛出“No return statement”错误吗?
【问题讨论】:
-
没有。没有导致外部循环被终止并因此无法返回值的代码路径。现在,如果
break终止了外循环,您将有一个观点。但唯一可以终止外循环的条件是return i或-1。