LeetCode014. Longest Common Prefix

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode014. Longest Common Prefix相关的知识,希望对你有一定的参考价值。

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

 

题解:

  简单的暴力遍历解决

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string>& strs) {
 4         int n = strs.size();
 5         if (n < 1 || strs[0].empty())
 6             return "";
 7         string res;
 8         
 9         for (int j = 0; j < strs[0].size(); ++j) {
10             char c = strs[0][j];
11             for (int i = 1; i < strs.size(); ++i) {
12                 if (j >= strs[i].size() || strs[i][j] != c)
13                     return res;
14             }
15             
16             res += c;
17         }
18         
19         return res;
20     }
21 };

 

以上是关于LeetCode014. Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

No.014:Longest Common Prefix

LeetCode-014-最长公共前缀

LeetCode刷题--点滴记录014

LeetCode--014--最长公共前缀

LeetCode--014--最长公共前缀(java)

LeetCode Longest Palindrome