diff --git a/cpp/0014-longest-common-prefix.cpp b/cpp/0014-longest-common-prefix.cpp index da43c223e..f4931a6f0 100644 --- a/cpp/0014-longest-common-prefix.cpp +++ b/cpp/0014-longest-common-prefix.cpp @@ -1,59 +1,28 @@ class Solution { public: - vector> res; - - vector> fourSum(vector& nums, int target) { - - if(nums.size() < 4) return res; - - vectorquad; - sort(nums.begin() , nums.end()); - kSum(0,4,target,nums,quad); - return res; - } - - - void kSum (int index , int k , long long target, vector nums , vector&q) - { - - if(k == 2) - { - twoSum(index , target, q , nums); - return; - } - - for(int i = index ; i < nums.size() - k + 1; i++) - { - if(i > index && nums[i] == nums[i-1]) continue; - q.push_back(nums[i]); - kSum(i+1 , k-1 , target-nums[i] , nums , q); - q.pop_back(); - } - - } - - void twoSum (int start,long long target,vector&ans,vector& nums) - { - int lo = start; - int hi = nums.size()-1; - - while(lo < hi) - { - int sum = nums[lo]+nums[hi]; - if(sum > target) hi--; - else if (sum < target) lo++; - - else - { - ans.insert(ans.end() , {nums[lo] , nums[hi]}); - res.push_back(ans); + string longestCommonPrefix(vector& strs) { + string result = strs[0]; + int charIndex = 0; - ans.pop_back(); - ans.pop_back(); - - lo++; - while (lo < hi && nums[lo] == nums[lo - 1]) lo++; - } - } - } + //finding minimum string length - that could be max common prefix + long maxCharIndex = strs[0].length(); + for (int i = 1; i < strs.size(); ++i) { + if (strs[i].length() < maxCharIndex) { + maxCharIndex = strs[i].length(); + } + } + + while (charIndex < maxCharIndex) { + char prevChar = strs[0][charIndex]; + for (int i = 1; i < strs.size(); ++i) { + if (prevChar == strs[i][charIndex]) { + continue; + } + return result.substr(0, charIndex); + } + ++charIndex; + result += prevChar; + } + return result.substr(0, charIndex); + } };