每日算法——letcode系列
Longest Common Prefix
Difficulty: Easy
Write a function to find the longest common prefix string amongst an array of strings.
class Solution {public: string longestCommonPrefix(vector& strs) { }};
翻译
最长公共前缀
难度系数:简单
写一个能够在字符串数组中找到最长公共前缀的函数。
思路
将字符串数组从第一个往后匹配就好, 并用函数
代码
class Solution {public: string longestCommonPrefix(vector& strs) { if (strs.empty()){ return ""; } for(int i = 0; i <= strs[0].size(); ++i){ string w = strs[0].substr(0, i); int j=1; for(j = 1; j < strs.size(); ++j){ if (strs[j][i] != strs[0][i]) { return strs[0].substr(0, i); } } } return strs[0]; }};