78. Longest Common Prefix
Description:
Given k strings, find the longest common prefix (LCP).
Example
Example 1:
Input: “ABCD”, “ABEF”, “ACEF”
Output: “A”
Example 2:
Input: “ABCDEFG”, “ABCEFG” and “ABCEFA”
Output: “ABC”
Main Idea:
String Problem. Using two for-loop to solve this problem, the first for-loop iterate each string, the second one iterate the character of string. Every time second for-loop complete, it means every string has one more common prefix.
Time/Space Cost:
Time Cost:
O
(
n
m
)
\ O(nm)
O(nm)
Space Cost:
O
(
1
)
\ O(1)
O(1)
Code:
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
// write your code here
string res = "";
if(strs.empty())
return res;
for(int j = 0; j < strs[0].size(); j++){
for(int i = 1; i < strs.size(); i++){
if(strs[i][j] != strs[0][j]){
return res;
}
}
res += strs[0][j];
}
return res;
}
};