工作生活

14. Longest Common Prefix 最长公共前缀

2019-07-04  本文已影响0人  xingzai

题目链接
tag:

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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读