File tree Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Original file line number Diff line number Diff line change @@ -667,10 +667,33 @@ \subsubsection{分析}
667
667
从位置0 开始,对每一个位置比较所有字符串,直到遇到一个不匹配。
668
668
669
669
670
- \subsubsection {代码}
670
+ \subsubsection {纵向扫描}
671
+ \begin {Code}
672
+ // LeetCode, Longest Common Prefix
673
+ // 纵向扫描,从位置0 开始,对每一个位置比较所有字符串,直到遇到一个不匹配
674
+ // 时间复杂度O(n1 +n2 +...)
675
+ // @author 周倩 (http://weibo.com/zhouditty)
676
+ class Solution {
677
+ public:
678
+ string longestCommonPrefix(vector<string> &strs) {
679
+ if (strs.empty()) return "" ;
680
+
681
+ for (int idx = 0; idx < strs[0].size(); ++idx) { // 纵向扫描
682
+ for (int i = 1; i < strs.size(); ++i) {
683
+ if (strs[i][idx] != strs[0][idx]) return strs[0].substr(0,idx);;
684
+ }
685
+ }
686
+ return strs[0];
687
+ }
688
+ };
689
+ \end {Code}
690
+
691
+
692
+ \subsubsection {横向扫描}
671
693
\begin {Code}
672
694
// LeetCode, Longest Common Prefix
673
- // 从位置0 开始,对每一个位置比较所有字符串,直到遇到一个不匹配
695
+ // 横向扫描,每个字符串与第0 个字符串,从左到右比较,直到遇到一个不匹配,
696
+ // 然后继续下一个字符串
674
697
// 时间复杂度O(n1 +n2 +...)
675
698
class Solution {
676
699
public:
@@ -680,7 +703,7 @@ \subsubsection{代码}
680
703
int right_most = strs[0].size() - 1;
681
704
for (size_t i = 1; i < strs.size(); i++)
682
705
for (int j = 0; j <= right_most; j++)
683
- if (strs[i][j] != strs[0][j])
706
+ if (strs[i][j] != strs[0][j]) // 不会越界,请参考string::[]的文档
684
707
right_most = j - 1;
685
708
686
709
return strs[0].substr(0, right_most + 1);
You can’t perform that action at this time.
0 commit comments