LeetCode:strStr 暴力美學

題目:

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路:暴力解決:

public String strStr(String haystack, String needle) {
		if (needle == null || haystack == null)
			return null;
		if (haystack.length() == 0 && needle.length() == 0)
			return haystack;
		if (needle.length() == 0)
			return haystack;
		for (int i = 0; i < haystack.length() - needle.length()+1; i++) {
			if (haystack.charAt(i) == needle.charAt(0)) {
				int x = i + 1;
				int j = 1;
				boolean flag = true;
				while (x < haystack.length() && j < needle.length()) {
					if (haystack.charAt(x) == needle.charAt(j)) {
						x++;
						j++;
					} else {
						flag = false;
						break;
					}
				}
				if (flag)
					return haystack.substring(i);
			}
		}
		return null;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章