From 593382dc0a9a1d3a972bc96515796a9ee2d10b72 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Wed, 12 Feb 2025 01:03:06 +0800 Subject: [PATCH] feat: 14_longest_common_prefix --- 14_longest_common_prefix/main.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 14_longest_common_prefix/main.cpp diff --git a/14_longest_common_prefix/main.cpp b/14_longest_common_prefix/main.cpp new file mode 100644 index 0000000..ecf69f8 --- /dev/null +++ b/14_longest_common_prefix/main.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) { + return ""; + } + + string result = ""; + + int longestLen = 0; + for (auto &str : strs) { + longestLen = max(longestLen, (int)str.length()); + } + + for (int i = 0; i < longestLen; i++) { + char currentChar = strs[0][i]; + for (auto &str : strs) { + if (currentChar != str[i]) { + return result; + } + } + result.push_back(currentChar); + } + + return result; + } +};