0%

LeetCode: 14. Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/

14. Longest Common Prefix

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

解题要点

  1. 注意题中要求的是前缀

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return string();
for(int i = 0; i < strs[0].size(); ++i)
{
for(int j = 0; j < strs.size(); ++j)
{
if (strs[j][i] != strs[0][i])
return strs[0].substr(0, i);
}
}
return strs[0];
}
};