From bd2df635f4f26bb4be0e9b1d6b3027f15bbcb392 Mon Sep 17 00:00:00 2001 From: vi Date: Sun, 11 Oct 2026 14:20:01 +0300 Subject: [PATCH] add leetcode/cpp/string/14.cpp file with the solution for the 14th leetcode task --- leetcode/cpp/string/14.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 leetcode/cpp/string/14.cpp diff --git a/leetcode/cpp/string/14.cpp b/leetcode/cpp/string/14.cpp new file mode 100644 index 0000000..8cf2b65 --- /dev/null +++ b/leetcode/cpp/string/14.cpp @@ -0,0 +1,38 @@ +/** + * 14. Longest Common Prefix + * 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 "". + */ + +/** + * example 1: + * input: str = [ "flower", "flow", "flight" ] + * output: "fl" + * + * + @author of the code is vi (yeah that's the nickname + */ + +class Solution { + constexpr static size_t THE_PREFIX_START_{0}; + +public: + constexpr inline std::string longestCommonPrefix(const std::vector& strs) noexcept { + std::string common_prefix{strs[0]}; + + // iterating through every string in strs + // e stands for element + for(const auto& e : strs) { + // if we didn't find the prefix, we'll change the prefix until we found it + while(e.find(common_prefix) != THE_PREFIX_START_) { + common_prefix = common_prefix.substr(0, common_prefix.size()-1); + // if common_prefix is an empty string, than it's over + if(common_prefix.empty()) { + return ""; + } + } + } + + return common_prefix; + } +};