Implement strStr()

题目描述
Implement strStr().

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

解题思路
本题最经典的算法是KMP算法,具体可以参考 http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html。自己采用BF算法这种基本算法实现的。

自己的代码
package leetcode;

public class ImplementStrStr {
	public String strStr(String haystack, String needle) {
		if(haystack == null || needle == null) return null;
		if(needle.length() > haystack.length()) return null;
		
		int hayLen = haystack.length();
		int needLen = needle.length();
		boolean isTrue = false;
		int sym = 0;
		for(int i = 0; i <= hayLen - needLen; i++){
			sym = i;
			int j = 0;
			for(; j < needLen; j++){
				if(needle.charAt(j) != haystack.charAt(i + j)) break;
			}
			if(needLen == j) {
				isTrue = true;
				break;
			}
		}
		if(isTrue) return haystack.substring(sym);
		else return null;
    }
	
	public static void main(String[] args) {
		String haystack = "";
		String needle = "";
		/*String haystack = "abcde";
		String needle = "bcde";*/
		
		ImplementStrStr iss = new ImplementStrStr();
		String s = iss.strStr(haystack, needle);
		System.out.println(s);
	}
}

你可能感兴趣的:(imp)