leetcode 014 —— Longest Common Prefix

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

思路:逐一比较各个字符串的prefix

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
	int n = strs.size();
	if (n == 0)
		return "";
	if (n == 1)
		return strs[0];
	int min = strs[0].size();
	for (int i = 1; i<strs.size(); i++)   //找到最短字符串
		min = strs[i].size()<min ? strs[i].size() : min;

	int i, j = 0;
	string s = "";
	for (i = 0; i < min; i++){  //string的元素坐标

		for (int j = 0; j < n - 1; j++){  //string的坐标,判断是否有相同的
			if (strs[j][i] != strs[j + 1][i])
			{
				return s;

			}
		}
		s = strs[0].substr(0, i + 1);
	}
	return s;
}
};




阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭