1. 程式人生 > >leetcode-14:Longest Common Prefix最長公共字首

leetcode-14:Longest Common Prefix最長公共字首

題目:

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 ""

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"

示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。

說明:

所有輸入只包含小寫字母 a-z 。

思路:先對字串序列排序,排完後只需要比較第一個和最後一個字串的字首即可,若他倆相等其他肯定相等。還需注意字串長度len應選擇最短那個字元。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()) return "";
        sort(strs.begin(),strs.end());
        int i=0,len=min(strs[0].size(),strs.back().size());
        while(i<len && strs[0][i]==strs.back()[i]) i++;
        return strs[0].substr(0,i);
    }
};