14. Longest Common Prefix 最长公共前缀

题目链接
tag:

  • Easy;

question:
  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.

思路:
  本题比较简单,只需要遍历第一个字符串的字符,如果当前字符的index大于后面的字符串长度,或者跟后面每个字符串的同位置字符不相同,则直接返回即可。代码如下:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string res = "";
        if (strs.empty())
            return res;
        if (strs.size() == 1)
            return strs[0];
        for (int i=0; i<strs[0].size(); ++i) {
            for (int j=1; j<strs.size(); ++j) {
                if (strs[j].size() < i || strs[0][i] != strs[j][i])
                    return res;
            }
            res += strs[0][i];
        }
        return res;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容