# 14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string `""`.

**Example 1:**

```
Input: ["flower","flow","flight"]
Output: "fl"
```

**Example 2:**

```
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
```

**Note:**

All given inputs are in lowercase letters `a-z`

## algorithm thought

以第一个字符串为基准，从第一个字符开始，对比所有字符串。出现不一样的就返回，都是一样的就加入到返回值后面。

## code

```
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()==1)
            return strs[0];
        if(strs.size()==0)
            return "";
        string res="";
        for(int i=0;i<strs[0].size();++i){
            for(int j=1;j<strs.size();++j){
                if(i==strs[j].size()||strs[0][i]!=strs[j][i]){
                    return res;
                }
            }
            res.push_back(strs[0][i]);
        }
        return res;
    }
};
```

## algorithm analysis

其实整个算法的逻辑是不需要判断size==1的，也就是第一行。但是如果不判断的话，就会在循环中一直判断并且调用push\_back到res中，会及其耗时间。加上第一个判断之后，整个代码运行时会快很多的。


---

# 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://kongchengzhuge.gitbook.io/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.
