| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.LongestCommonPrefix; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestCommonPrefixDivideAndConquer : ILongestCommonPrefix |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(S), where S is the sum of all characters in all strings |
| | 19 | | /// Space complexity - O(S), where S is the sum of all characters in all strings |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="strs"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public string LongestCommonPrefix(string[] strs) |
| 32 | 24 | | { |
| 32 | 25 | | switch (strs.Length) |
| | 26 | | { |
| | 27 | | case > 2: |
| 9 | 28 | | { |
| 9 | 29 | | var partLength = strs.Length / 2; |
| 9 | 30 | | var leftPart = strs.Take(partLength).ToArray(); |
| 9 | 31 | | var rightPart = strs.Skip(partLength).Take(strs.Length - partLength).ToArray(); |
| | 32 | |
|
| 9 | 33 | | return GetLongestPrefix(LongestCommonPrefix(leftPart), LongestCommonPrefix(rightPart)); |
| | 34 | | } |
| | 35 | | case 2: |
| 15 | 36 | | { |
| 15 | 37 | | return GetLongestPrefix(strs[0], strs[1]); |
| | 38 | | } |
| | 39 | | case 1: |
| 8 | 40 | | return strs[0]; |
| | 41 | | } |
| | 42 | |
|
| 0 | 43 | | return string.Empty; |
| 32 | 44 | | } |
| | 45 | |
|
| | 46 | | private static string GetLongestPrefix(string str1, string str2) |
| 24 | 47 | | { |
| 24 | 48 | | var minLength = Math.Min(str1.Length, str2.Length); |
| 24 | 49 | | var prefixLength = 0; |
| | 50 | |
|
| 230 | 51 | | for (var i = 0; i < minLength; i++) |
| 101 | 52 | | { |
| 101 | 53 | | if (str1[i] == str2[i]) |
| 91 | 54 | | { |
| 91 | 55 | | prefixLength++; |
| 91 | 56 | | } |
| | 57 | | else |
| 10 | 58 | | { |
| 10 | 59 | | break; |
| | 60 | | } |
| 91 | 61 | | } |
| | 62 | |
|
| 24 | 63 | | return str1[..prefixLength]; |
| 24 | 64 | | } |
| | 65 | | } |