LeetCode Problem -- 14. Longest Common Prefix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/85949789
  • 描述: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.

  • 分析:给出多个string,要求找出这多个string中最长公共前缀。所谓公共前缀是从第一个字符进行比较得到的。
  • 思路一:将给出的string分为三种情况:
    1.给出string为空,return “”
    2.只给出一个string,return strs[0]
    3.给出两个及以上string,先比较前两个,得到一个共同前缀,对第三个及之后的只需和所得的公共前缀进行比较,若有不同元素,则对公共前缀中的元素进行删除,最终得到最长公共前缀。
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        if (strs.size() == 1) return strs[0];
        string common_str = "";
        for (int i = 0; i < strs[0].size(); i++) {
            if (i >= strs[1].size() || strs[0][i] != strs[1][i]) break;
            else if (strs[0][i] == strs[1][i]) common_str += strs[0][i];
        }
        for (int i = 2; i < strs.size(); i++) {
            if (strs[i].empty()) return "";
            for (int j = 0; j < common_str.size(); j++) {
                if (common_str[j] != strs[i][j]) {
                    common_str.erase(j, common_str.size());
                    break;
                }
            }
        }
        return common_str;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/85949789