【leetcode】14. Longest Common Prefix(C)

Description:

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 “”.

Example1:

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example2:

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.

题目链接

提交代码:

char* longestCommonPrefix(char** strs, int strsSize) {
    int i, p = 0, flag = 1;
	char* prefix = (char*)malloc(10000 * sizeof(char));
	char tmp;

	while (flag&&strs[0][p]!='\0')
	{
		//设置当前第一个字符串的第p个字符为标杆
		tmp = strs[0][p];
		for (i = 1; i < strsSize; i++)
		{
			if (strs[i][p] != tmp||strs[i][p]=='\0')
			{
				flag = 0;
				break;
			}
		}
		//退出for循环表示已经轮完一遍所有字符和标杆字符一样
        if(flag!=0)
		    prefix[p++] = tmp;
	}
	prefix[p] = '\0';

	return prefix;
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83178465