|
| 1 | +package com.anas.leetcode.easy; |
| 2 | + |
| 3 | +public class LongestCommonPrefix { |
| 4 | + public String longestCommonPrefix(String[] strs) { |
| 5 | + String commonPrefix = strs[0]; |
| 6 | + for (int i = 1; i < strs.length; i++) { |
| 7 | + String str = strs[i]; |
| 8 | + if (commonPrefix.length() > str.length()) // if common prefix length less than str length |
| 9 | + commonPrefix = commonPrefix.substring(0, str.length()); // set common prefix to str length |
| 10 | + for (int j = commonPrefix.length() - 1; j >= 0; j--) { |
| 11 | + if (commonPrefix.charAt(j) != str.charAt(j)) { |
| 12 | + commonPrefix = commonPrefix.substring(0, j); // remove char |
| 13 | + j = commonPrefix.length(); // update j |
| 14 | + } |
| 15 | + |
| 16 | + } |
| 17 | + } |
| 18 | + return commonPrefix; |
| 19 | + } |
| 20 | + |
| 21 | + public static void main(String[] args) { |
| 22 | + LongestCommonPrefix lo = new LongestCommonPrefix(); |
| 23 | + // Test 2 |
| 24 | + System.out.println(lo.longestCommonPrefix(new String[]{"flower","flow","flight"})); |
| 25 | + // Test 1 |
| 26 | + System.out.println(lo.longestCommonPrefix(new String[]{"dog","racecar","car"})); |
| 27 | + // Test 3 |
| 28 | + System.out.println(lo.longestCommonPrefix(new String[]{"cir","car"})); |
| 29 | + } |
| 30 | +} |
0 commit comments