Sunday搜尋演算法實現
阿新 • • 發佈:2018-12-13
int MAXSIZE = 256; int moveLength[MAXSIZE]; void getMoveLength(const string &T) { int tLen = T.size(); for(int i = 0; i < MAXSIZE; ++ i) moveLength[i] = tLen + 1; for(int i = 0; T[i]; ++ i) moveLength[T[i]] = tLen - i; } int Sunday(const string& S, const string &T) { getMoveLength(T); int tLen = T.size(); int sLen = S.size(); int i = 0; while(i < sLen) { int j = 0; for( ; j < tLen && i + j < sLen && S[i + j] == T[j]; ++ j) ; if(j >= tLen) return i; if(i + tLen > sLen) return -1; i += moveLength[S[i + tLen]]; } return -1; }