首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

LeetCode 28 Implement strStr():子串查找朴素實現

     編輯:關於C++

題目描述

實現 strStr():返回 needle 在 haystack 中首次出現的下標,不存在返回 -1。若 needle 為空返回 0。

朴素算法 (Brute Force)

雙重循環:外層枚舉 haystack 起始位置 i,內層比對 needle 每個字符。時間 O((n-m+1)m),對短模式串足夠。

參考代碼 (C)

bool isSub(char *str, char *sub) {
    int len = strlen(sub);
    for (int i = 0; i < len; ++i)
        if (str[i] != sub[i]) return false;
    return true;
}

int strStr(char *haystack, char *needle) {
    int hlen = strlen(haystack), nlen = strlen(needle);
    if (hlen == nlen && isSub(haystack, needle)) return 0;
    for (int i = 0; i <= hlen - nlen; ++i)
        if (isSub(haystack + i, needle)) return i;
    return -1;
}

進階算法提示

  • KMP:預處理 next 數組,O(n+m)。
  • Boyer-Moore / Sunday:實踐中更快。
  • C++ 可直接用 string::find。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved