14. Longest Common Prefix

来源:互联网 发布:淘宝上代购dw手表600 编辑:程序博客网 时间:2024/06/09 14:53

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

寻找最长公共前缀。

思路:先sort排序,再对第0和第n-1项对比即可。

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        int i, j, n = strs.size();        if (n == 0) return "";        sort(strs.begin() ,strs.begin() + n);        for (j = 0; j < strs[0].size() && j < strs[n - 1].size() && strs[0][j] == strs[n - 1][j]; j++);        return strs[0].substr(0, j);    }};


0 0