首页 > 代码库 > Leetcode | Longest Common Prefix

Leetcode | 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         if (strs.empty()) return ""; 5         if (strs.size() == 1) return strs[0]; 6         for (int len = 0; ; len++) { 7             for (int i = 1; i < strs.size(); ++i) { 8                 if (len >= strs[i].length() || len >= strs[i - 1].length() || strs[i][len] != strs[i - 1][len]) { 9                     if (len > 0) return strs[0].substr(0, len);10                     else return "";11                 }12             }13         }14         return "";15     }16 };

 

Leetcode | Longest Common Prefix