# 最长公共前缀

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E7%AE%80%E5%8D%95\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#简单) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E5%AD%97%E7%AC%A6%E4%B8%B2\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#字符串) [![](https://img.shields.io/static/v1?label=\&message=%E6%95%B0%E7%BB%84/%E7%9F%A9%E9%98%B5\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/..#数组矩阵)

> [最长公共前缀\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47)

**问题简述**

```
给你一个大小为 n 的字符串数组 strs ，其中包含n个字符串 , 编写一个函数来查找字符串数组中的最长公共前缀，返回这个公共前缀。
```

**思路**

* 利用 Python 内置的 `zip` 函数每次纵向取所有字符串的第 `i` 个字符；
* 对这些字符 `set` 后，如果都相同，则加入前缀，否则退出循环，返回结果；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def longestCommonPrefix(self , strs: List[str]) -> str:
        
        ret = []
        for it in zip(*strs):
            if len(set(it)) == 1:
                ret.append(it[0])
            else:
                break
        
        return ''.join(ret)
```

</details>
