王廷瑋|數位醫療|智慧醫療: 14. Longest Common Prefix WFU

2024年7月2日 星期二

14. Longest Common Prefix

14. Longest Common Prefix


編寫一個函數來查找字符串數組中的最長公共前綴。

如果沒有公共前綴,則返回空字符串 ""。

範例 1:

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


Python


class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
# Assume the first string is the common prefix initially
prefix = strs[0]
for string in strs[1:]:
# Update the prefix length until it matches the start of the string
while string.find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix

12.01MB, 17ms


C++


#include <string>
#include <vector>

using namespace std;

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) {
return "";
}

// Assume the first string is the common prefix initially
string prefix = strs[0];

// Iterate over each string in the vector starting from the second string
for (int i = 1; i < strs.size(); ++i) {
// Update the prefix length until it matches the start of the string
while (strs[i].find(prefix) != 0) {
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) {
return "";
}
}
}

return prefix;
}
};

11.1MB, 3ms


Javascript


/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 0) {
return "";
}

// Assume the first string is the common prefix initially
let prefix = strs[0];

// Iterate over each string in the array starting from the second string
for (let i = 1; i < strs.length; i++) {
// Update the prefix length until it matches the start of the string
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (prefix === "") {
return "";
}
}
}

return prefix;
};

48.9MB, 54ms