| 1 | // Licensed under the GNU Free Documentation License 1.2 |
| 2 | // https://www.gnu.org/licenses/old-licenses/fdl-1.2.en.html |
| 3 | // |
| 4 | // Source: https://rosettacode.org/wiki/Longest_common_prefix#Go |
| 5 | |
| 6 | package util |
| 7 | |
| 8 | func LongestCommonPrefix(list []string) string { |
| 9 | // Special cases first |
| 10 | switch len(list) { |
| 11 | case 0: |
| 12 | return "" |
| 13 | case 1: |
| 14 | return list[0] |
| 15 | } |
| 16 | |
| 17 | // LCP of min and max (lexigraphically) |
| 18 | // is the LCP of the whole set. |
| 19 | min, max := list[0], list[0] |
| 20 | for _, s := range list[1:] { |
| 21 | switch { |
| 22 | case s < min: |
| 23 | min = s |
| 24 | case s > max: |
| 25 | max = s |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | for i := 0; i < len(min) && i < len(max); i++ { |
| 30 | if min[i] != max[i] { |
| 31 | return min[:i] |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // In the case where lengths are not equal but all bytes |
| 36 | // are equal, min is the answer ("foo" < "foobar"). |
| 37 | return min |
| 38 | } |