leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

longest-common-prefix.cpp (771B)


      1 #include <iostream>
      2 #include <vector>
      3 using namespace std;
      4 
      5 //Runtime: 3ms Beats: 87.33%
      6 //Memory: 9.3MB Beats: 54.69%
      7 
      8 string longestCommonPrefix(vector<string>& strs) {
      9     int shortest = strs[0].size();
     10     for(int i = 1 ; i < strs.size() ; ++i){
     11         if(strs[i].size() < shortest){
     12             shortest = strs[i].size();
     13         }
     14     }
     15     char current;
     16     string output = "";
     17     for(int i = 0 ; i < shortest ; ++i){
     18         current = strs[0][i];
     19         for(int x = 0 ; x < strs.size() ; ++x){
     20             if(strs[x][i] != current){
     21                 return output;
     22             }
     23         }
     24         output += current;
     25     }
     26     return output;
     27 }
     28 
     29 
     30 
     31 int main(){
     32     vector<string> strings = {"Cat","Cap", "Cab"};
     33     cout << longestCommonPrefix(strings) << endl;
     34 }