admin管理员组

文章数量:1636952

https://leetcode/problems/implement-strstr/#/description


Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.



package go.jacob.day719;

/**
 * 28. Implement strStr()
 * 
 * @author Jacob 题意是:判断needle是否为haystack的子串
 */
public class Demo4 {
	/*
	 * 判断needle是否为haystack的子串,是则返回第一个index,否则返回-1;
	 */
	public int strStr(String haystack, String needle) {
		if (haystack == null || needle == null || haystack.length() < needle.length())
			return -1;
		if (needle.length() == 0)
			return 0;
		for (int i = 0; i <= haystack.length() - needle.length(); i++) {
			if (haystack.substring(i, i + needle.length()).equals(needle))
				return i;
		}

		return -1;
	}

	/*
	 * 牛客网解答
	 */
	public String strStr_niuke(String haystack, String needle) {
		if (haystack == null || needle == null || haystack.length() < needle.length())
			return null;
		if (needle.length() == 0)
			return haystack.substring(0);
		for (int i = 0; i <= haystack.length() - needle.length(); i++) {
			for (int j = 0; j < needle.length(); j++) {
				if (haystack.substring(i, i + needle.length()).equals(needle))
					return haystack.substring(i);

			}
		}
		return null;
	}
}


本文标签: LeetCodeimplementJavastrStr