// sunday: string match algorithm intsunday_strStr(string &text, string &pattern){ // 对应的字符最后一次出现在pattern中的位置 int num[128]; for (int i = 0; i < 128; i++) { // init the length, the char never show in pattern num[i] = pattern.size() + 1; } for (int i = 0; i < pattern.size(); i++){ num[pattern[i]] = pattern.size() - i; } int ans = -1; //i起始位置 + pattern的长度 <= 文本长度,就一直匹配;一轮匹配之后pattern的指针重置为0 for (int i = 0, j = 0; i + pattern.size() <= text.size(); j = 0) { while (j < pattern.size() && pattern[j] == text[i+j]) { j++; } // match success if (j == pattern.size()) { //i do not move ans = i; break; } // match failed, then i = i + num[?] i += num[text[i + pattern.size()]]; } return ans; }