Saturday, September 20, 2014

LeetCode: Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.


   string longestCommonPrefix(vector<string> &strs) {  
     int n = strs.size();  
     if (n == 0){string s; return s;}  
     if (n == 1){return strs[0];}  
     int length = 0;  
     int x = strs[0].length();  
     string res = strs[0];  
     for (int i = 1; i < n; i++)  
     {  
       int y = strs[i].length();  
       if(y < x)x = y;  
     }  
     bool success;  
     for (int i = 0; i < x; i++)  
     {  
       for (int j = 1; j<n; j++)  
       {  
         success = false;  
         if(strs[0][i] != strs[j][i])  
         {  
           break;  
         }  
         else  
           success = true;  
       }  
       if(success)length++;  
       else break;  
     }  
     return res.substr(0,length);  
   }  

No comments:

Post a Comment