LeetCode_Longest Common Prefix

2258 ワード

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 ;

    }

};