File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ // 纵向扫描
2+ // Time Complexity: O(m*n)
3+ // Space Complexity: O(1)
4+
5+ # include < iostream>
6+ # include < vector>
7+ # include < string>
8+ using namespace std ;
9+
10+ class Solution {
11+ public:
12+ string longestCommonPrefix (vector<string>& strs) {
13+ if (!strs.size ()) {
14+ return " " ;
15+ }
16+ // 以第一个字符串为基准
17+ int length = strs[0 ].size ();
18+ // 字符串个数
19+ int count = strs.size ();
20+ for (int i = 0 ; i < length; ++i) {
21+ char c = strs[0 ][i];
22+ for (int j = 1 ; j < count; ++j) {
23+ // 如果当前字符不相等或者已经到达某个字符串的末尾
24+ if (i == strs[j].size () || strs[j][i] != c) {
25+ return strs[0 ].substr (0 , i);
26+ }
27+ }
28+ }
29+ return strs[0 ];
30+ }
31+ };
32+
33+ int main () {
34+ Solution solution;
35+ vector<string> strs = {" flower" , " flow" , " flight" };
36+ cout << solution.longestCommonPrefix (strs) << endl;
37+ return 0 ;
38+ }
You can’t perform that action at this time.
0 commit comments