一、题目内容

image.png

二、题解

解法1:

思路

二分

代码

  1. public class Solution {
  2. /**
  3. *
  4. * @param strs string字符串一维数组
  5. * @return string字符串
  6. */
  7. public String longestCommonPrefix (String[] strs) {
  8. // write code here
  9. if (strs == null || strs.length == 0) {
  10. return "";
  11. }
  12. int minLength = Integer.MAX_VALUE;
  13. for (String str : strs) {
  14. // 获取最短字符串的长度
  15. minLength = Math.min(minLength, str.length());
  16. }
  17. // 二分查找
  18. int low = 0, high = minLength;
  19. while (low < high) {
  20. // 分别对前后两部分进行判断
  21. int mid = (high - low + 1) / 2 + low;
  22. if (isCommonPrefix(strs, mid)) {
  23. low = mid;
  24. } else {
  25. high = mid - 1;
  26. }
  27. }
  28. return strs[0].substring(0, low);
  29. }
  30. // 判断长度为 length 的字符是否是strs的共同字串
  31. public boolean isCommonPrefix(String[] strs, int length) {
  32. String str0 = strs[0].substring(0, length);
  33. int count = strs.length;
  34. for (int i = 1; i < count; i++) {
  35. String str = strs[i];
  36. for (int j = 0; j < length; j++) {
  37. if (str0.charAt(j) != str.charAt(j)) {
  38. return false;
  39. }
  40. }
  41. }
  42. return true;
  43. }
  44. }