public 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;
}
}
}
Elegant Java solution

@jeantimex said in Elegant Java solution:
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;
}
}Nice!

Very concise! I think my solution is more intuitive though. Thanks for sharing!
public int strStr(String s, String t) { if (t.isEmpty()) return 0; // edge case: "",""=>0 "a",""=>0 for (int i = 0; i <= s.length()  t.length(); i++) { for (int j = 0; j < t.length() && s.charAt(i + j) == t.charAt(j); j++) if (j == t.length()  1) return i; } return 1; }

@imaginationsuper The break is to break the inner loop. The outer loop is still valid.

@seeioung I think this is because all the return situations are handled within the loop. If you add a return statement at the very end of the code, you will find it is unreachable.
