title: Daily Practice (35): Longest Common Prefix
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/14
Daily practice (35): Longest common prefix
Write a function to find the longest common prefix in an array of strings.
If no common prefix exists, the empty string "" is returned.
Example 1:
Input: strs = ["flower","flow","flight"]
output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
output: ""
Explanation: The input does not have a common prefix.
hint:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of lowercase English letters only
Source: LeetCode
Link: https://leetcode-cn.com/problems/longest-common-prefix
Method 1: Compare character by character
Thought analysis
Compare the first with the second, save the common prefix, then compare with the third, and so on
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) {
return "";
}
string ans = strs[0];//先从strs[0]开始,与后面一个比较
for (int i = 0; i < strs.size(); i++) {
string s = ans;//保存上次的公共前缀
ans = "";
for (int j = 0; j < strs[i].size(); j++) {
if (s[j] == strs[i][j]) {
ans += s[j];
} else { //遇到不一样的就退出循环
break;
}
}
if (ans == "") {
break;
}
}
return ans;
}
Method 2: Double pointer
Algorithm flow:
First find out the lexicographically smallest and largest strings in the array, and the longest common prefix is the common prefix of the two strings
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) {
return "";
}
const auto p = minmax_element(strs.begin(), strs.end());
for (int i = 0; i < p.first->size(); i++) {
if (p.first->at(i) != p.second->at(i)) {
return p.first->substr(0, i);
}
}
return *p.first;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。