From 20463a604d4c23541354d20df474cd071292bee0 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Thu, 3 Nov 2022 16:27:54 +0800 Subject: [PATCH] s0014 --- include/s0014_longest_common_prefix.hpp | 14 +++++++++++++ src/s0014_longest_common_prefix.cpp | 26 +++++++++++++++++++++++++ tests/s0014_longest_common_prefix.cpp | 17 ++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 include/s0014_longest_common_prefix.hpp create mode 100644 src/s0014_longest_common_prefix.cpp create mode 100644 tests/s0014_longest_common_prefix.cpp diff --git a/include/s0014_longest_common_prefix.hpp b/include/s0014_longest_common_prefix.hpp new file mode 100644 index 0000000..65d2fc3 --- /dev/null +++ b/include/s0014_longest_common_prefix.hpp @@ -0,0 +1,14 @@ +#ifndef S0014_LONGEST_COMMON_PREFIX +#define S0014_LONGEST_COMMON_PREFIX + +#include +#include + +using namespace std; + +class Solution { + public: + string longestCommonPrefix(vector& strs); +}; + +#endif diff --git a/src/s0014_longest_common_prefix.cpp b/src/s0014_longest_common_prefix.cpp new file mode 100644 index 0000000..a8e0cca --- /dev/null +++ b/src/s0014_longest_common_prefix.cpp @@ -0,0 +1,26 @@ +#include "s0014_longest_common_prefix.hpp" + +string Solution::longestCommonPrefix(vector& 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; +} diff --git a/tests/s0014_longest_common_prefix.cpp b/tests/s0014_longest_common_prefix.cpp new file mode 100644 index 0000000..f39a8fa --- /dev/null +++ b/tests/s0014_longest_common_prefix.cpp @@ -0,0 +1,17 @@ +#include "s0014_longest_common_prefix.hpp" + +#include + +TEST(Problem14, Case1) { + vector i{"flower","flow","flight"}; + string o{"fl"}; + Solution solution; + EXPECT_EQ(solution.longestCommonPrefix(i), o); +} + +TEST(Problem14, Case2) { + vector i{"dog","racecar","car"}; + string o{""}; + Solution solution; + EXPECT_EQ(solution.longestCommonPrefix(i), o); +}