/*
 * Algorithm: Vertical scanning / 縱向掃描
 * 跟 C 版本同一套邏輯：以 strs[0] 為基準，逐欄掃描。
 * 用 std::string::substr 直接切出答案，不必手動管理記憶體。
 * Same logic as the C version; std::string::substr handles the slicing and memory.
 */

#include <string>     // std::string — C++ 字串型別 / C++ managed string type
#include <vector>     // std::vector — 動態陣列 / dynamic array

class Solution {
public:
    // strs 用 const& 傳入避免複製整個 vector / pass by const reference to avoid copying
    std::string longestCommonPrefix(std::vector<std::string>& strs) {
        // 題目保證 strs 至少有 1 個元素，但保險判斷一下 / guard against empty input
        if (strs.empty()) return "";

        // 取出第一個字串作為參考；用 const& 避免複製 / reference to strs[0], no copy
        const std::string& first = strs[0];

        // i 代表目前比對到第幾欄 / current column being checked
        for (size_t i = 0; i < first.size(); i++) {
            char c = first[i];   // 期望的字元 / expected character at column i

            // range-for 逐一拿出每個字串 (從 index 1 開始我們手動跳過第一個)
            // Iterate every string; we skip strs[0] inside the loop with a check.
            for (size_t j = 1; j < strs.size(); j++) {
                // 兩個 fail 條件: 字串長度不足 i+1，或第 i 個字元不對
                // Two failure conditions: string too short, or character mismatch.
                if (i >= strs[j].size() || strs[j][i] != c) {
                    // substr(0, i) 取出 first 的前 i 個字元 / first i chars of `first`
                    // 這就是當前能確定的最長共同前綴 / that's the LCP found so far
                    return first.substr(0, i);
                }
            }
        }

        // 走完整個 first 都沒有 mismatch，代表 first 本身就是 LCP
        // (例如 strs = ["abc","abcdef"] 時答案是 "abc")
        // If we exhausted first without any mismatch, first itself is the LCP.
        return first;
    }
};
