首页 > 代码库 > Leetcode Longest Common Prefix

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) {        if(strs.empty()) return "";        int minLength = strs[0].length();        for(int i = 0 ; i < strs.size(); ++ i) minLength = min(minLength,(int)strs[i].length());        bool flag = false;        int i = 0;        for(i = 0 ; i < minLength; ++ i){            char ch = strs[0][i];            for(int j = 1; j < strs.size(); ++ j){                if(strs[j][i]!=ch){flag=true;break;}            }            if(flag) break;        }        return strs[0].substr(0,i);    }};