Skip to content

14. 最长公共前缀 #4

@MyLinChi

Description

@MyLinChi

题目描述

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

链接:https://leetcode-cn.com/problems/longest-common-prefix

解决方案 1(自己写的)

基本思想是假设最长公共前缀的长度为0,然后一直增加到最大为止。
需要注意的是判断字符串集为空集或者只含有一个元素的特殊情况。

class Solution {
public:
	string longestCommonPrefix(vector<string>& strs) {
		if (strs.size() == 0)return "";
		else if (strs.size() == 1)return strs[0];
		int comlen = -1;
		while (true){
			comlen++;
			for (int i = 0; i<strs.size() - 1; i++){
				if (comlen >= strs[i].length())return strs[0].substr(0, comlen);
				if (strs[i][comlen] != strs[i + 1][comlen])return strs[0].substr(0, comlen);
			}
		}
		return strs[0].substr(0, comlen);
	}
};

方案二(官方)

N个string的公共最长前缀子串为两个string得到的最长前缀子串与第三个string求最长公共前缀子串。

class Solution {
public:
	string longestCommonPrefix(vector<string>& strs) {
		if (strs.size() == 0)return "";
		string pre = strs[0];
		for (int i = 1; i < strs.size(); i++)
		{
			int j = 0;
			while (j < pre.length() && j < strs[i].length() && pre[j] == strs[i][j])j++;
			pre = pre.substr(0,j);
		}
		return pre;
	}
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions