14.Longest Common Prefix (String)

2224 ワード

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

public:

    string longestCommonPrefix(vector<string>& strs) {

        int vSize = strs.size();

        string result = "";

        if(vSize == 0) return result;

        else if(vSize == 1) return strs[0];

        

        result = strs[0];

        int i,j;

        for(i = 1; i < vSize; i++){

            for(j = 0; j < result.length() && j < strs[i].length(); j++){

                if(strs[i][j] != result[j]) break;

            }

            result = result.substr(0,j); // 

        }

        return result;

    }

};