[LeetCode] Longest Common Prefix

来源:互联网 发布:可以做引流网站的源码 编辑:程序博客网 时间:2024/04/28 01:09

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    int n =strs.size();if ( n==0 ) return string();int minL=INT_MAX;for(int i=0;i<n;i++)minL=min(minL,(int)strs[i].length());int p=0;string ans;while(p<minL){char ch=strs[0][p];for(int i=0;i<n;i++)if (strs[i][p]!=ch)return ans;ans.push_back(ch);        p++;}return ans;            }};


原创粉丝点击