| | 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 LongestCommonPrefixHorizontalScanning : ILongestCommonPrefix |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(S), where S is the sum of all characters in all strings |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="strs"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public string LongestCommonPrefix(string[] strs) |
| 14 | 24 | | { |
| 14 | 25 | | var firstString = strs[0]; |
| | 26 | |
|
| 14 | 27 | | if (string.IsNullOrEmpty(firstString)) |
| 1 | 28 | | { |
| 1 | 29 | | return string.Empty; |
| | 30 | | } |
| | 31 | |
|
| 50 | 32 | | var minLength = strs.Min(str => str.Length); |
| 13 | 33 | | var prefixLength = 0; |
| | 34 | |
|
| 110 | 35 | | for (var i = 0; i < minLength; i++) |
| 47 | 36 | | { |
| 186 | 37 | | if (strs.All(str => str[i] == firstString[i])) |
| 42 | 38 | | { |
| 42 | 39 | | prefixLength++; |
| 42 | 40 | | } |
| | 41 | | else |
| 5 | 42 | | { |
| 5 | 43 | | break; |
| | 44 | | } |
| 42 | 45 | | } |
| | 46 | |
|
| 13 | 47 | | return firstString[..prefixLength]; |
| 14 | 48 | | } |
| | 49 | | } |