Leetcode Study Day 10

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 “”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

My solution

My idea is to compare the character of one word to the others which are in the same position. If all the characters on the same position are same, we add this character to our return string, then we go to the next position, once the characters are not the same, we return the string. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string commonPrefix = "";
for (int i = 0; i < strs[0].size(); i++){
char cache = strs[0][i];
for (int j = 1; j < strs.size(); j++){
if (strs[j][i] == cache)
cache = strs[j][i];
else
return commonPrefix;
}
commonPrefix += cache;
}
return commonPrefix;
}
};

Sort lexicographically solution

The main idea of this solution is that:

If the array is sorted alphabetically then you can assume that the first element of the array and the last element of the array will have most different prefixes of all comparisons that could be made between strings in the array. If this is true, you only have to compare these two strings.

And this is the step:

  1. Initialize an empty string ans to store the common prefix.
  2. Sort the input list v lexicographically. This step is necessary because the common prefix should be common to all the strings, so we need to find the common prefix of the first and last string in the sorted list.
  3. Iterate through the characters of the first and last string in the sorted list, stopping at the length of the shorter string.
  4. If the current character of the first string is not equal to the current character of the last string, return the common prefix found so far.
  5. Otherwise, append the current character to the ans string.
  6. Return the ans string containing the longest common prefix.

And this is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string longestCommonPrefix(vector<string>& v) {
string ans="";
sort(v.begin(),v.end());
int n=v.size();
string first=v[0],last=v[n-1];
for(int i=0;i<min(first.size(),last.size());i++){
if(first[i]!=last[i]){
return ans;
}
ans+=first[i];
}
return ans;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信