Leetcode: Longest Common Prefix

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

可以做Trie树,不过实现起来比较复杂,貌似时间复杂度也不低。干脆直接比较,也能通过。

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        string result;
        if (strs.empty()) {
            return result;
        }
        
        result = strs[0];
        for (int i = 1; i < strs.size(); ++i) {
            int j = 0;
            int common = result.size();
            while (j < common && j < strs[i].size()) {
                if (result[j] != strs[i][j]) {
                    break;
                }
                ++j;
            }
            result = result.substr(0, j);
        }
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)