LeetCode 14 最长公共前缀

mac2025-09-17  36

LeetCode 14 最长公共前缀

题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2:

输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。

分析

两层遍历即可,注意遍历次数。

C++ 代码

class Solution { public: string longestCommonPrefix(vector<string>& strs) { bool end = false; string res; int len = -1; for(int i = 0; i < strs.size(); i++){ if(len == -1 || len < strs[i].length()) len = strs[i].length(); } for(int i = 0; i < len; i++){ char t = strs[0][i]; for(int j = 0; j < strs.size(); j++){ if(t != strs[j][i]){ end = true; break; } } if(end == true) break; res += t; } return res; } };
最新回复(0)