【LeetCode算法练习(C++)】Longest Common Prefix

来源:互联网 发布:深圳网络指尖公司 编辑:程序博客网 时间:2024/06/09 17:01

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

链接:Longest Common Prefix
解法:逐个字符比较,时间O(N*L),N是字符串个数,L是最长前缀的长度

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        int siz = strs.size();        if (siz == 0) return "";        else if (siz == 1) return strs[0];        string ans;        for (int i = 0; i < strs[0].length(); i++) {            for (int j = 1; j < siz; j++) {                if (strs[j - 1][i] != strs[j][i]) return ans;            }            ans += strs[0][i];        }        return ans;    }};

Runtime: 6 ms

原创粉丝点击