码迷,mamicode.com
首页 > 其他好文 > 详细

14. Longest Common Prefix

时间:2018-01-18 22:03:30      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:http   字符串   problem   etc   公共子串   leetcode   ring   com   code   

14. Longest Common Prefix

题目

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

解析

  • leetcode官网给出了水平,垂直,二分,trie树的方法;但是感觉都需要把所有字符串遍历一遍,考虑用简单的水平遍历
class Solution_14 {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if (strs.size() == 0)
        {
            return ""; //返回NULL 错误
        }
        if (strs.size() == 1)
        {
            string str = strs[0];
            return str;
        }
        string ret = strs[0];
        int max_comlen = ret.size();
        int j = 0;
        for (int i = 1; i < strs.size(); i++)
        {
            j = 0;
            while (strs[i][j] == ret[j] && j < ret.size()) //优化:记录上一次匹配最远的位置,下一次不超过这个距离
            {
                j++;
            }
            max_comlen = min(max_comlen, j); //取的是最小长度的公共子串;min=('a','a','b')=0;
        }
        return ret.substr(0, max_comlen);
    }
};

题目来源

14. Longest Common Prefix

标签:http   字符串   problem   etc   公共子串   leetcode   ring   com   code   

原文地址:https://www.cnblogs.com/ranjiewen/p/8313049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!