Sunday, May 10, 2015

Longest Common Prefix

来源:Leetcode

原帖:http://oj.leetcode.com/problems/longest-common-prefix/

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

代码:
 class Solution {  
 public:  
   string longestCommonPrefix(vector<string> &strs) {  
     string res;  
     if (strs.empty()) return res;      
     for (int i = 0; i < strs[0].size(); ++i) {  
       char ch = strs[0][i];  
       for (int j = 1; j < strs.size(); ++j) {  
         if (i == strs[j].size() || strs[j][i] != ch) { // termination  
           return res;                    
         }  
       }  
       res.push_back(ch);  
     }  
     return res;  
   }  
 };  

No comments:

Post a Comment