LeetCode Longest Common Prefix

来源:互联网 发布:数控车倒螺纹编程实例 编辑:程序博客网 时间:2024/06/02 22:45

Longest Common Prefix

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

Solution:

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(strs.empty())            return "";        string result=strs[0];        for(int i=1;i<strs.size();++i){            for(int j=0;j<result.size();++j){                if(j>strs[i].size()-1||strs[i][j]!=result[j]){                    result=result.substr(0,j);                    break;                }            }        }        return result;    }};