28. Implement strStr()

说重点,这个题办法很多,上学的时候有一章专门讲的这个。。
先用个简单的写了再说吧,pocket gems的面试似乎重点不在实现KMP之类的问题上。。

public class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.length() > haystack.length()) return -1;
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            boolean found = true;
            for (int j = 0; j < needle.length(); j++) {
                if (needle.charAt(j) != haystack.charAt(i+j)) {
                    found = false;
                    break;
                }
            }
            if (found) return i;
        }
        
        return -1;
    }
}



三刷。

这遍主要目的就是implement KMP.

仔细去学习了一下,资料很多,目前来说最好的是这个。
https://www.youtube.com/watch?v=GTJr8OvyEVQ)印度口音中算说得很好很好的了。。

中文资料也有,不过实际上通过文字叙述比较复杂。

KMP的实现主要是通过pattern建立next[]。

public int[] generateNext(String s) {
		int j = 0;
		int[] res = s.length();

		for (int i = 1; i < s.length(); i++) {
			while (j > 0 && s.charAt(i) != s.charAt(j)) {
				j = res[j - 1];
			}

			if (s.charAt(i) == s.charAt(j)) {
				j += 1;
			}

			res[i] = j;

		}

		return res;
	}

里面i是遍历指针,j是固定指针(自己编的名字)。

然后使用strStr和建立next()如出一辙。。

public class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack.length() < needle.length()) return -1;
        if (needle.length() == 0) return 0;
        
        int[] next = getNext(needle);
        
        int j = 0;
        
        for (int i = 0; i < haystack.length(); i ++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            
            if (haystack.charAt(i) == needle.charAt(j)) {
                j += 1;
            }
            
            if (j == needle.length()) {
                return i - j + 1;
            }
        }
        
        return -1;
    }
    
    public int[] getNext (String s) {
        int[] res = new int[s.length()];
        int j = 0;
        
        for (int i = 1; i < s.length(); i ++) {
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = res[j - 1];
            }
            
            if (s.charAt(j) == s.charAt(i)) {
                j += 1;
            }
            
            res[i] = j;
        }
        
        return res;
    }
    

}

第一次在课上学觉得挺难的。。认真搞一搞其实很容易。。

posted @ 2016-10-28 04:44  哇呀呀..生气啦~  阅读(113)  评论(0)    收藏  举报