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; + } +};