标签:c style class blog code java
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 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; } };
下标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