实现String的indexOf功能:给定一个haystack和一个needle,返回needle在haystack中第一次出现的index,如果不出现,则返回-1(如果needle为空,则返回0)。如haystack = “hello”,needle = “ll”, 则返回2.
一种“优雅的方法”:
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; } } }