14. Longest Common Prefix

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

Example 1:

Input: ["flower","flow","flight"] Output: "fl"

Example 2:

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 flag = true;
    int i = 0;
    int idx = 0;
    char ch;
    
    if (strsSize == 0)
        return "";
    
    while (true) {
        flag = true;
        ch = strs[0][idx];
        for (i = 0; i < strsSize; i++) {
            if (strs[i][idx] == '\0' || ch != strs[i][idx]) {
                flag = false;
                break;
            }
        }
        if (!flag)
            break;
        idx++;
    }
    
    strs[0][idx] = '\0';
    return strs[0];
}

leetcode 题解汇总

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:14. Longest Common Prefix

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/192.html

相关文章