-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongest_common_prefix.cpp
60 lines (49 loc) · 1.09 KB
/
Longest_common_prefix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*https://leetcode.com/problems/longest-common-prefix/description/*/
/*optimal*/
class Solution {
public:
string longestCommonPrefix(vector<string>& s) {
sort(s.begin(),s.end());
string s1=s[0];
string s2=s[s.size()-1];
string ans="";
for(int i=0;i<s1.length();i++)
{
if(s1[i]==s2[i])
{
ans+=s1[i];
}
else
{
return ans;
}
}
return ans;
}
};
/*greedy */
class Solution {
public:
string longestCommonPrefix(vector<string>& s) {
if(s.empty()) return "";
string temp=s[0];
int mini=INT_MAX;
string ans="";
for(int i=1;i<s.size();i++)
{ int count=0;
for(int j=0;j<s[i].size();j++)
{
if(s[0][j]==s[i][j])
{
count++;
}
}
mini=min(mini,count);
}
for(int i=0;i<mini;i++)
{
ans+=s[0][i];
}
return ans;
}
};