14_最長公共字首

zeta186012發表於2024-09-10

14_最長公共字首

【問題描述】

編寫一個函式來查詢字串陣列中的最長公共字首。如果不存在公共字首,返回空字串 ""

示例一:
輸入:strs = ["flower","flow","flight"]
輸出:"fl"

示例二:
輸入:strs = ["dog","racecar","car"]
輸出:""
解釋:輸入不存在公共字首。

【演算法設計思想】

在本題中,我們可以從第一個字串開始,以第一個字串為基準,每次從第一個字串中取出一個字元,然後在從第二個字元開始遍歷到字串陣列的末尾。我們看後面的是否都滿足我們的要求,如果都滿足的話,那麼我們可以加入到我們想要的結果中。如果有一個不滿足,那麼我們直接從第一個字串開始截斷就好了。

【演算法描述】

C++:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0][i];
            for (int j = 1; j < strs.size(); j++) {
                if (i == strs[j].length() || c != strs[j][i]) {
                    return strs[0].substr(0, i);
                }
            }
        }

        return strs[0];
    }
};

Java:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        String first = strs[0];
        for (int i = 0; i < first.length(); i++) {
            char c = first.charAt(i);

            for (int j = 1; j < strs.length; j++) {
                String temp = strs[j];
                if (i == temp.length() || c != temp.charAt(i)) {
                    return first.substring(0, i);
                }
            }
        }
        return first;
    }
}

Python:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        size = len(strs)
        len1 = len(strs[0])
        first = strs[0]
        for i in range(len1):
            c =  first[i]
            for j in range(1,size):
                temp = strs[j]
                if i == len(temp) or c != temp[i]:
                    return first[0:i]
        
        return first

C語言:

char* longestCommonPrefix(char** strs, int strsSize) {
    if (strsSize == 0) {
        return NULL;
    }

    char* first = strs[0];
    int len = strlen(first);

    // Allocate space for the result
    char* result = malloc(len + 1);
    if (!result) {
        return NULL;  // Memory allocation failed
    }
    result[0] = '\0';  // Initialize result with empty string

    for (int i = 0; i < len; i++) {
        char c = first[i];

        for (int j = 1; j < strsSize; j++) {
            char* temp = strs[j];
            if (i == strlen(temp) || c != temp[i]) {
                // Found a mismatch, truncate the result and return it
                result[i] = '\0';
                return result;
            }
        }

        // Append the character to the result string
        strncat(result, &first[i], 1);
    }

    // If all strings have the same prefix, return the entire first string
    return result;
}

相關文章