【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;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007275777
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞