首页 > 代码库 > leetcode 14. Longest Common Prefix

leetcode 14. Longest Common Prefix

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

把输入strs当做二维数组,对每一列j, 检查strs[0...n-1][j]是否相同。

 1 string longestCommonPrefix(vector<string> &strs)  2     { 3         string max_prefix = ""; 4          5         if (strs.size() <= 0) 6             return max_prefix; 7         for (int j = 0; j < strs[0].size(); j++) 8         { 9             for (int i = 1; i < strs.size(); i++)10             {11                 if ((strs[i].size() <= j) || (strs[0][j] != strs[i][j]))12                     return max_prefix;13             }14             max_prefix += strs[0][j];15         }16         17         return max_prefix;18     }

 

leetcode 14. Longest Common Prefix