// 演算法 / Algorithm:
// 與 C 版相同：雙指針暴力搜尋，外層枚舉起點，內層比對字元。
// Same as the C version: brute-force two-pointer scan.
// 這裡使用 std::string 的 .size() 與 operator[] 取代 strlen / 指針運算。
// We use std::string's .size() and operator[] instead of strlen / raw pointers.

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = (int)haystack.size();   // .size() 是 O(1)，回傳字元數 / .size() is O(1), returns char count
        int m = (int)needle.size();     // 同上，存進 int 方便做減法 / store as int to allow subtraction safely

        if (m > n) return -1;           // needle 太長不可能匹配 / needle longer than haystack ⇒ no match

        // 外層 i：嘗試把 needle 對齊到 haystack 的位置 i
        // Outer i: align needle's start with haystack[i]
        // i <= n - m 確保 haystack[i..i+m-1] 不會越界
        // i <= n - m guarantees haystack[i..i+m-1] stays in bounds
        for (int i = 0; i <= n - m; ++i) {
            int j = 0;                  // 內層指針，比對 needle 字元 / inner pointer over needle
            // operator[] 取得指定索引的字元，不做邊界檢查（速度快）
            // operator[] returns the char at that index; no bounds check (fast)
            while (j < m && haystack[i + j] == needle[j]) {
                ++j;                    // 前置遞增，C++ 中習慣寫 ++j 而非 j++ / idiomatic pre-increment in C++
            }
            if (j == m) {               // 全部 m 個字元都對上 / matched all m chars
                return i;               // 回傳起點 / return start index
            }
        }

        return -1;                      // 找不到 / not found
    }
};
