-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestCommonPrefix.cpp
46 lines (40 loc) · 1.13 KB
/
longestCommonPrefix.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
#include <string>
#include <vector>
#include <iostream>
// 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 "".
class Solution {
public:
std::string longestCommonPrefix(const std::vector<std::string>& items) {
std::string result;
std::size_t index = 0;
while(true)
{
char prefix = 0;
std::size_t count = 0;
for(std::size_t i = 0; i < items.size(); ++i)
{
const auto& item = items[i];
if(item.size() > index)
{
if(prefix == 0)
prefix = item[index];
if(item[index] == prefix)
++count;
}
}
++index;
if(count == items.size())
result += prefix;
else
return result;
}
return {};
}
};
int main()
{
Solution s;
std::cout << s.longestCommonPrefix({"flower","flow","flight"}) << "\n"; // fl
return 0;
}