纵向扫描

  1. package com.alg.Three;
  2. /** 最长公共前缀
  3. * 纵向挨个比对字符是否相同
  4. * @author fuyao
  5. * @date 2022年06月20日 5:08 下午
  6. */
  7. public class LongestCommonPrefix {
  8. public String longestCommonPrefix(String[] strs) {
  9. if (strs == null || strs.length == 0){
  10. return "";
  11. }
  12. int length = strs[0].length();
  13. int count = strs.length;
  14. for (int i = 0; i < length; i++) {
  15. for (int j = 1; j < count; j++) {
  16. if (strs[j].length() == i || strs[j].charAt(i) != strs[0].charAt(i)){
  17. return strs[0].substring(i);
  18. }
  19. }
  20. }
  21. return strs[0];
  22. }
  23. }

分治法

  1. public String longestCommonPrefix1(String[] strs) {
  2. if (strs == null || strs.length == 0) {
  3. return "";
  4. } else {
  5. return longestCommonPrefix(strs, 0, strs.length - 1);
  6. }
  7. }
  8. private String longestCommonPrefix(String[] strs, int start, int end) {
  9. if (start == end) {
  10. return strs[start];
  11. } else {
  12. int mid = (end - start) / 2 + start;
  13. String lcpLeft = longestCommonPrefix(strs, start, mid);
  14. String lcpRight = longestCommonPrefix(strs, mid + 1, end);
  15. return commonPrefix(lcpLeft, lcpRight);
  16. }
  17. }
  18. private String commonPrefix(String lcpLeft, String lcpRight) {
  19. int minlength = Math.min(lcpLeft.length(), lcpRight.length());
  20. for (int i = 0; i < minlength; i++) {
  21. if (lcpLeft.charAt(i) != lcpRight.charAt(i)) {
  22. return lcpLeft.substring(0, i);
  23. }
  24. }
  25. return lcpLeft.substring(0, minlength);
  26. }

二分法

  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (strs == null || strs.length == 0) {
  4. return "";
  5. }
  6. int minLength = Integer.MAX_VALUE;
  7. for (String str : strs) {
  8. minLength = Math.min(minLength, str.length());
  9. }
  10. int low = 0, high = minLength;
  11. while (low < high) {
  12. int mid = (high - low + 1) / 2 + low;
  13. if (isCommonPrefix(strs, mid)) {
  14. low = mid;
  15. } else {
  16. high = mid - 1;
  17. }
  18. }
  19. return strs[0].substring(0, low);
  20. }
  21. public boolean isCommonPrefix(String[] strs, int length) {
  22. String str0 = strs[0].substring(0, length);
  23. int count = strs.length;
  24. for (int i = 1; i < count; i++) {
  25. String str = strs[i];
  26. for (int j = 0; j < length; j++) {
  27. if (str0.charAt(j) != str.charAt(j)) {
  28. return false;
  29. }
  30. }
  31. }
  32. return true;
  33. }
  34. }