LeetCode Longest Common Prefix

LeetCode Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.


这题简单,找一系列字符串的最长公共前缀。先找出最短的字符串s,长度为sz,然后依次检查每个字符串的前sz个字符是否相同,只要有一个不相同就返回。

完整代码如下:

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

本代码提交AC,用时4MS。

Leave a Reply

Your email address will not be published. Required fields are marked *