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
72 声望28 粉丝

行万里路,读万卷书