Skip to content

Commit ae7f58d

Browse files
committed
longest common prefix
1 parent 1021e35 commit ae7f58d

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Longest Common Prefix
3+
=====================
4+
5+
Write a function to find the longest common prefix string amongst an array of strings.
6+
7+
If there is no common prefix, return an empty string "".
8+
9+
Example 1:
10+
Input: strs = ["flower","flow","flight"]
11+
Output: "fl"
12+
13+
Example 2:
14+
Input: strs = ["dog","racecar","car"]
15+
Output: ""
16+
Explanation: There is no common prefix among the input strings.
17+
18+
Constraints:
19+
1 <= strs.length <= 200
20+
0 <= strs[i].length <= 200
21+
strs[i] consists of only lower-case English letters.
22+
*/
23+
24+
class Solution
25+
{
26+
public:
27+
string longestCommonPrefix(vector<string> &strs)
28+
{
29+
string ans;
30+
int minLen = INT_MAX;
31+
for (auto &i : strs)
32+
minLen = min(minLen, (int)i.size());
33+
for (int i = 0; i < minLen; ++i)
34+
{
35+
int ch = strs[0][i];
36+
for (int j = 1; j < strs.size(); ++j)
37+
{
38+
if (strs[j][i] != ch)
39+
return ans;
40+
}
41+
ans += ch;
42+
}
43+
return ans;
44+
}
45+
};

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@
138138
- [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) - [Cpp Soultion](./Day-15/Integer%20to%20Roman.cpp)
139139
- [Implement strStr](https://leetcode.com/problems/implement-strstr/) - [Cpp Soultion](./Day-15/Implement%20strStr.cpp)
140140
- [String to Integer](https://leetcode.com/problems/string-to-integer-atoi/) - [Cpp Soultion](./Day-15/String%20to%20Integer.cpp)
141-
- []() - [Cpp Soultion](./Day-15/.cpp)
141+
- [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) - [Cpp Soultion](./Day-15/Longest%20Common%20Prefix.cpp)
142142
- []() - [Cpp Soultion](./Day-15/.cpp)
143143

144144
###

0 commit comments

Comments
 (0)