【Leetcode】14. Longest Common Prefix 两个字符串的最长公共前缀长度
文章目录
1. 题目
Write a function to find the longest common prefix string amongst an array of strings.
2. 思路
遍历按序逐个比较,直接了当。
3. 代码
耗时:6ms
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string cm;
int cm_i = 0;
int n = strs.size();
if (n == 0) return cm;
if (n == 1) return strs[0];
while (true) {
char label = strs[0][cm_i];
for (int s_i = 1; s_i < n; s_i++) {
if (cm_i >= strs[s_i].length() || strs[s_i][cm_i] != label) return cm;
}
cm += label;
cm_i++;
}
return cm;
}
};

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论