实现strStr()

一.题目

实现strStr()

二.思路

needle 作为外循环,haystack 作为内循环,注意这里 if ((index + needle.length() - 1) > (haystack.length() - 1))

	public int strStr(String haystack, String needle) {
		if (needle.equals("")) {
			return 0;
		}
		int index = 0;
		for (int i = 0; i < needle.length(); i++) {
			for (int j = 0; j < haystack.length(); j++) {
				if (haystack.charAt(j) == needle.charAt(i)) {
					index = j;
					if ((index + needle.length() - 1) > (haystack.length() - 1)) {
						return -1;
					} else if (haystack.substring(index,
							index + needle.length()).equals(needle)) {
						return index;
					}
				}
			}
		}
		return -1;
	}