Longest Common Prefix问题及解法

来源:互联网 发布:ubuntu命令行中文乱码 编辑:程序博客网 时间:2024/06/15 02:34

问题描述:

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.size() == 0 ) return "";        string pre = "";        for(int i = 0; i < strs[0].length(); i++)        {        char c = strs[0][i];        for(int j = 0; j < strs.size(); j++)        {        string s = strs[j];        if(s.length() < i + 1 || c != s[i])        return pre;}pre.append(1,c);}return pre;    }};


0 0
原创粉丝点击