14 Longest Common Prefix

1 题目

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.

2 尝试解

2.1 分析

以第一个单词为依据,判断第i个字符是否与其他单词的第i个字符相等,如果是,结果添加此字符,如果超出其他单词范围或不相等,返回已有结果。

2.2 代码

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

3 标准解

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string prefix = "";
        for(int idx=0; strs.size()>0; prefix+=strs[0][idx], idx++)
            for(int i=0; i<strs.size(); i++)
                if(idx >= strs[i].size() ||(i > 0 && strs[i][idx] != strs[i-1][idx]))
                    return prefix;
        return prefix;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_39145266/article/details/89884853