#14 Longest Common Prefix

題目鏈接:https://leetcode.com/problems/longest-common-prefix/


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


char* longestCommonPrefix(char** strs, int strsSize) {
    int i, j = 0;
    if(strsSize <= 0 || strs == NULL)       //沒有字符串,輸出空串
        return strs;
    if(strsSize == 1)       //只有一個字符串,直接輸出第一個字符串
        return strs[0];
    while(1) {
        for(i = 1; i < strsSize; ++i)
            if(strs[0][j] == '\0' || strs[i][j] != strs[0][j]) {
                strs[0][j] = '\0';
                return strs[0];
            }
        ++j;
    }
}


發佈了96 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章