LeetCode 14. 最长公共前缀 Longest Common Prefix(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/84872007

题目描述:

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

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

示例 1:

输入: [“flower”,“flow”,“flight”]
输出: “fl”

示例 2:

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

说明:

所有输入只包含小写字母 a-z 。

题目解答:

方法1:两层循环

该题比较简单,取第一个单词的index位置字符,然后遍历其它所有单词该位置是否为该字符,不是则结束,是则继续下一个位置。注意输入可能为空。运行时间0ms,代码如下。

char* longestCommonPrefix(char** strs, int strsSize) {
    if(strsSize == 0) {
        char* result = (char*)calloc(1, sizeof(char));
        return result;
    }
    int index = 0, i = 0;
    char flag = strs[0][index];
    while(flag) {
        for(i = 1; i < strsSize; i++) {
            if(strs[i][index] != flag)
                break;
        }
        if(i < strsSize)
            break;
        flag = strs[0][++index];
    }
    strs[0][index] = '\0';
    return strs[0];
}

猜你喜欢

转载自blog.csdn.net/hang404/article/details/84872007