Skip to content

Commit ade70c3

Browse files
committed
添加了横向扫描,感谢@周婧
1 parent e4228e7 commit ade70c3

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

C++/LeetCodet题解(C++版).pdf

3.87 KB
Binary file not shown.

C++/chapString.tex

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -667,10 +667,33 @@ \subsubsection{分析}
667667
从位置0开始,对每一个位置比较所有字符串,直到遇到一个不匹配。
668668
669669
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{横向扫描}
671693
\begin{Code}
672694
// LeetCode, Longest Common Prefix
673-
// 从位置0开始,对每一个位置比较所有字符串,直到遇到一个不匹配
695+
// 横向扫描,每个字符串与第0个字符串,从左到右比较,直到遇到一个不匹配,
696+
// 然后继续下一个字符串
674697
// 时间复杂度O(n1+n2+...)
675698
class Solution {
676699
public:
@@ -680,7 +703,7 @@ \subsubsection{代码}
680703
int right_most = strs[0].size() - 1;
681704
for (size_t i = 1; i < strs.size(); i++)
682705
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::[]的文档
684707
right_most = j - 1;
685708
686709
return strs[0].substr(0, right_most + 1);

0 commit comments

Comments
 (0)