|
| 1 | +package com.leetcode.strings; |
| 2 | + |
| 3 | +/** |
| 4 | + * Problem: https://leetcode.com/problems/longest-common-prefix/ |
| 5 | + * |
| 6 | + * @author rampatra |
| 7 | + * @since 2019-04-20 |
| 8 | + */ |
| 9 | +public class LongestCommonPrefix { |
| 10 | + |
| 11 | + /** |
| 12 | + * Time complexity: O(r * c) |
| 13 | + * where, |
| 14 | + * r = no. of strings |
| 15 | + * c = max. no. of characters in a particular string |
| 16 | + * <p> |
| 17 | + * Runtime: <a href="https://leetcode.com/submissions/detail/223735469/">1 ms</a>. |
| 18 | + * |
| 19 | + * @param strs |
| 20 | + * @return |
| 21 | + */ |
| 22 | + public static String longestCommonPrefix(String[] strs) { |
| 23 | + StringBuilder sb = new StringBuilder(); |
| 24 | + |
| 25 | + int row; |
| 26 | + for (int col = 0; col < Integer.MAX_VALUE; col++) { |
| 27 | + for (row = 0; row < strs.length - 1; row++) { |
| 28 | + // once we find a different character under one column, break the loop |
| 29 | + if (col == strs[row].length() |
| 30 | + || col == strs[row + 1].length() |
| 31 | + || strs[row].charAt(col) != strs[row + 1].charAt(col)) { |
| 32 | + break; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // check the row counter to figure whether all characters in a particular column are identical |
| 37 | + if (row == strs.length - 1 && strs[0].length() > 0 && col < strs[0].length()) { |
| 38 | + sb.append(strs[0].charAt(col)); |
| 39 | + } else { |
| 40 | + break; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return sb.toString(); |
| 45 | + } |
| 46 | + |
| 47 | + public static void main(String[] args) { |
| 48 | + System.out.println(longestCommonPrefix(new String[]{})); |
| 49 | + System.out.println(longestCommonPrefix(new String[]{""})); |
| 50 | + System.out.println(longestCommonPrefix(new String[]{"a"})); |
| 51 | + System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"})); |
| 52 | + System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"})); |
| 53 | + } |
| 54 | +} |
0 commit comments