|
| 1 | +package top.itning.test; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +/** |
| 7 | + * 14. 最长公共前缀 |
| 8 | + * 编写一个函数来查找字符串数组中的最长公共前缀。 |
| 9 | + * <p> |
| 10 | + * 如果不存在公共前缀,返回空字符串 ""。 |
| 11 | + * |
| 12 | + * @author itning |
| 13 | + * @since 2021/12/7 14:27 |
| 14 | + */ |
| 15 | +public class LongestCommonPrefixTest { |
| 16 | + @Test |
| 17 | + void longestCommonPrefixTest() { |
| 18 | + Assertions.assertEquals("fl", longestCommonPrefix(new String[]{"flower", "flow", "flight"})); |
| 19 | + Assertions.assertEquals("", longestCommonPrefix(new String[]{"dog", "racecar", "car"})); |
| 20 | + Assertions.assertEquals("", longestCommonPrefix(new String[]{"", "racecar", "car"})); |
| 21 | + } |
| 22 | + |
| 23 | + public String longestCommonPrefix(String[] strs) { |
| 24 | + // 1 <= strs.length <= 200 |
| 25 | + // 0 <= strs[i].length <= 200 |
| 26 | + // strs[i] 仅由小写英文字母组成 |
| 27 | + int l = Integer.MAX_VALUE; |
| 28 | + for (String str : strs) { |
| 29 | + l = Math.min(l, str.length()); |
| 30 | + } |
| 31 | + if (l == Integer.MAX_VALUE || l == 0) { |
| 32 | + return ""; |
| 33 | + } |
| 34 | + StringBuilder sb = new StringBuilder(); |
| 35 | + a: |
| 36 | + for (int i = 0; i < l; i++) { |
| 37 | + for (int j = 0; j < strs.length; j++) { |
| 38 | + char c = strs[j].charAt(i); |
| 39 | + if (j + 1 != strs.length) { |
| 40 | + char cc = strs[j + 1].charAt(i); |
| 41 | + if (cc != c) { |
| 42 | + break a; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + sb.append(strs[0].charAt(i)); |
| 47 | + } |
| 48 | + return sb.toString(); |
| 49 | + } |
| 50 | +} |
0 commit comments