LeetCode_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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string result="";
        if(strs.size() == 0) return result ;
        
        string first = strs[0] ;
        
        for(int i = 0; i < first.size() ;i++)
        {
           char c = first[i] ;
           for(int j =1 ; j< strs.size(); j++)
             if(i > strs[j].size() -1 ||  c != strs[j][i])
                 return result;
                 
            result+=c;
        }
        
        return result ;
    }
};

 

posted @ 2013-07-24 22:01  冰点猎手  阅读(152)  评论(0编辑  收藏  举报