面试经典150题——Day20
文章目录
- 一、题目
- 二、题解
一、题目
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: strs = [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
Input: strs = [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
题目来源: leetcode
二、题解
class Solution {
public:string longestCommonPrefix(vector<string>& strs) {int n = strs.size();int count = strs[0].length();for(int i = 0;i < n - 1;i++){int len1 = strs[i].length();int len2 = strs[i + 1].length();int tmp = 0;for(int j = 0;j < len1 && j < len2;j++){if(strs[i][j] == strs[i + 1][j]) tmp++;else break;}count = min(count,tmp);}string res = "";for(int i = 0;i < count;i++) res += strs[0][i];return res;}
};