# 14. Longest Common Prefix

## 1.問題

![](/files/-LL_2vwbzRf-cSNo9Oqr)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法
  * 用vector\<int> 儲存每個string各字母出現的次數, 當相同字母的出現次數與字串數量相同時, increment + 1
* 測試計算複雜度: O(n)

## **3.程式碼**

```
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int size = strs.size();
        if (size == 0) {
            return "";
        }
        vector<char> v(128, 0);
        string s = "";
        int maxNum = INT_MAX;
        for (int i = 0; i < size; i++) {
            maxNum = min(maxNum, int(strs[i].size()));
        }

        for (int j = 0; j < maxNum; j++) {
            for (int i = 0; i < size; i++) {
                v[int(strs[i][j] - '0')]++;
            }
            if (v[int(strs[0][j] - '0')] == size) {
                s.push_back(strs[0][j]);
                v[int(strs[0][j] - '0')] = 0;
            } else {
                return s;
            }
        }
        return s;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/14.-longest-common-prefix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
