LeeCode27:Implement strStr()

来源:互联网 发布:改键位软件 编辑:程序博客网 时间:2024/05/25 19:58

Implement strStr().

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

public class Solution {    public String strStr(String haystack, String needle) {        // Start typing your Java solution below        // DO NOT write main() function        String res = null;        if(needle.length()==0)            return haystack;        if(needle.length()!=0 && haystack.length()==0)            return res;        // build Table                int cnd=0, pos=2;        int [] next = new int[needle.length()];        next[0]=-1;        if(needle.length()>1)            next[1]=0;        while(pos<needle.length()){            // forward            if(needle.charAt(cnd)==needle.charAt(pos-1)){                cnd++;                next[pos]=cnd;                pos++;            }            // fall back            else if(cnd>0){                cnd = next[cnd];                continue;            }            // unluck no macth            else{                next[pos]=0;                pos++;            }        }                int hPos=0, nPos=0;        while(hPos+nPos<haystack.length()){            if(haystack.charAt(hPos+nPos)==needle.charAt(nPos)){                nPos++;                if(nPos == needle.length()){                    res = haystack.substring(hPos);                    break;                }            }            else{                hPos = hPos+nPos-next[nPos];                if(next[nPos]!=-1)                    nPos = next[nPos];                else                    nPos = 0;            }        }        return res;    }}