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
.
定義i和j,i是遍歷字串中的字元,j是遍歷字串集中的每個字串。把單詞上下排好,相當於一個各行長度有可能不相等的二維陣列,採用縱向逐列遍歷,在遍歷的過程中,如果某一行沒有了,說明其為最短的單詞,因共同字首的長度不能長於最短單詞,此時返回已經找出的共同字首。每取出第一個字串的某一個位置的單詞,然後遍歷其他所有字串的對應位置看是否相等,如果有不滿足的直接返回res,如果都相同,則將當前字元存入結果,繼續檢查下一個位置的字元,程式碼如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string res = "";
for (int j = 0; j < strs[0].size(); ++j) {
char c = strs[0][j];
for (int i = 1; i < strs.size(); ++i) {
if (j >= strs[i].size() || strs[i][j] != c) {
return res;
}
}
res.push_back(c);
}
return res;
}
};