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

Leetcode:Longest Common Prefix 最长公共前缀

时间:2014-06-10 08:29:55      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

戳我去解题

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

 

bubuko.com,布布扣
class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if (strs.size() == 0) return "";
        string res;
        for (int i = 0; ; ++i) {
            int j = 0;
            for (j = 0; j < strs.size(); ++j) {
                if (i >= strs.at(j).size() || strs.at(0).at(i) != strs.at(j).at(i)) break;
            }
            if (j < strs.size()) break;
            res += strs.at(0).at(i);
        }
        return res;
    }
};
bubuko.com,布布扣

下标i指示第一个字符串,下标j指示vector

a   b  c

a   b  d  e  f

a   b  d  e

a   b  c  d

我们采用纵向比较,首先比较 纵向4个a,然后纵向4个b,然后到第三列的d,发现不相同

比较过程中,我们需要注意:

1.  下标i值必须小于 每一行字符串长度

2.   一旦发现一个与第一行同列不相同的值就break

我们可以知道:

如果整列都相同,则j值一定等于 strs.size()  此时添加该公共字符

如果 j值小于 strs.size(),则意味着有不相同的值(因为提前break了),这时就中断外层循环

 

Leetcode:Longest Common Prefix 最长公共前缀,布布扣,bubuko.com

Leetcode:Longest Common Prefix 最长公共前缀

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3778574.html

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