# 14. Longest Common Prefix
Difficulty: Easy
## Solution
```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-09-28
**/
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
struct TestCaseStruct {
vector<string> input;
string expected_output;
};
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.empty()) {
return string("");
}
string output;
bool is_common_prefix_continued = true;
char current_char;
size_t index = 0;
while (is_common_prefix_continued) {
current_char = strs[0][index];
for (const auto &str : strs) {
if (str.size() <= index || str[index] != current_char) {
is_common_prefix_continued = false;
break;
}
}
if (is_common_prefix_continued) {
output += current_char;
}
++index;
}
return output;
}
};
int main(int argc, char *argv[]) {
vector<TestCaseStruct> test_cases = {{{"flower", "flow", "fly"}, "fl"},
{{"dog", "racecar", "car"}, ""}};
int test_case_index = 0;
Solution solution;
for (auto &test_case : test_cases) {
if (solution.longestCommonPrefix(test_case.input) ==
test_case.expected_output) {
cout << "test_case[" << test_case_index << "] is pass." << endl;
} else {
cout << "test_case[" << test_case_index << "] is fail." << endl;
}
++test_case_index;
}
/*
vector<string> test_case_1 = {"flower", "flow", "fly"};
vector<string> test_case_2 = {"dog", "racecar", "car"};
Solution solution;
auto output_1 = solution.longestCommonPrefix(test_case_1);
auto output_2 = solution.longestCommonPrefix(test_case_2);
std::cout << "output_1 = [" << output_1 << "]" << std::endl;
std::cout << "output_2 = [" << output_2 << "]" << std::endl;
*/
return EXIT_SUCCESS;
}
```
## Result
Success
Details
Runtime: 8 ms, faster than 70.27% of C++ online submissions for Longest Common Prefix.
Memory Usage: 9.4 MB, less than 43.58% of C++ online submissions for Longest Common Prefix.
###### tags: `LeetCode-Easy` `C++`