This commit is contained in:
parent
0df74464b7
commit
20463a604d
14
include/s0014_longest_common_prefix.hpp
Normal file
14
include/s0014_longest_common_prefix.hpp
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef S0014_LONGEST_COMMON_PREFIX
|
||||
#define S0014_LONGEST_COMMON_PREFIX
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
string longestCommonPrefix(vector<string>& strs);
|
||||
};
|
||||
|
||||
#endif
|
26
src/s0014_longest_common_prefix.cpp
Normal file
26
src/s0014_longest_common_prefix.cpp
Normal file
@ -0,0 +1,26 @@
|
||||
#include "s0014_longest_common_prefix.hpp"
|
||||
|
||||
string Solution::longestCommonPrefix(vector<string>& strs) {
|
||||
string o{""};
|
||||
int size = strs.size();
|
||||
int minLen = strs.at(0).length();
|
||||
for (int i{0}; i < size; i++) {
|
||||
if (strs.at(i).length() < minLen) {
|
||||
minLen = strs.at(i).length();
|
||||
}
|
||||
}
|
||||
// string index
|
||||
for (int i{0}; i < minLen; i++) {
|
||||
string tmp = strs.at(0).substr(i, 1);
|
||||
// vector index
|
||||
for (int j{0}; j < size; j++) {
|
||||
if (strs.at(j).substr(i, 1) == tmp) {
|
||||
continue;
|
||||
} else {
|
||||
return o;
|
||||
}
|
||||
}
|
||||
o.append(tmp);
|
||||
}
|
||||
return o;
|
||||
}
|
17
tests/s0014_longest_common_prefix.cpp
Normal file
17
tests/s0014_longest_common_prefix.cpp
Normal file
@ -0,0 +1,17 @@
|
||||
#include "s0014_longest_common_prefix.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem14, Case1) {
|
||||
vector<string> i{"flower","flow","flight"};
|
||||
string o{"fl"};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestCommonPrefix(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem14, Case2) {
|
||||
vector<string> i{"dog","racecar","car"};
|
||||
string o{""};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestCommonPrefix(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user