
Sponsored
In this approach, you start with the first string as a reference and gradually compare it with each subsequent string in the array. The reference prefix is shortened until it matches the prefixes of all strings.
Time Complexity: O(S), where S is the sum of all characters in all strings.
Space Complexity: O(1), as we are using constant extra space.
1class Solution:
2 def longestCommonPrefix(self, strs):
3 if not strs:
4 return ""
5 prefix = strs[0]
6 for s in strs[1:]:
7 while not s.startswith(prefix):
8 prefix = prefix[:-1]
9 if not prefix:
10 return ""
11 return prefix
12
13if __name__ == "__main__":
14 sol = Solution()
15 print(sol.longestCommonPrefix(["flower", "flow", "flight"]))Python readily facilitates string manipulation. Using startswith, we efficiently trim the prefix for each string until a match is found or it becomes empty.
This approach involves dividing the array of strings into two halves, recursively finding the longest common prefix for each half, and merging the results. The merge step compares characters from the two strings to find the common prefix.
Time Complexity: O(S), where S is the sum of all characters in the strings.
Space Complexity: O(M*logN), where M is the length of the common prefix and N is the number of strings.
1
class Solution {
private string CommonPrefix(string left, string right) {
int minLength = Math.Min(left.Length, right.Length);
for (int i = 0; i < minLength; i++) {
if (left[i] != right[i]) {
return left.Substring(0, i);
}
}
return left.Substring(0, minLength);
}
private string DivideAndConquer(string[] strs, int left, int right) {
if (left == right) {
return strs[left];
} else {
int mid = (left + right) / 2;
string lcpLeft = DivideAndConquer(strs, left, mid);
string lcpRight = DivideAndConquer(strs, mid + 1, right);
return CommonPrefix(lcpLeft, lcpRight);
}
}
public string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
return DivideAndConquer(strs, 0, strs.Length - 1);
}
static void Main(string[] args) {
var sol = new Solution();
string[] strs = { "flower", "flow", "flight" };
Console.WriteLine(sol.LongestCommonPrefix(strs));
}
}C# efficiently divides and processes string input leveraging recursion, culminating in a consolidated prefix assembled via character-by-character matching.