当前位置:   article > 正文

LeetCode-最长公共前缀(java实现)_最长公共前缀java

最长公共前缀java

    题目如图,

 

    最开始我的想法是利用双重for循环,对于相邻字符串的每个字符进行比较。例如"flower"和"flow",最长公共前缀就是'flo',利用一个计数器保存公共前缀的长度3;然后比较"flow"和"flight"的最长公共前缀,长度为2,也用计数器保存。最后在这个计数器数组中找到最小值,就是整个String数组中所有元素的最长公共前缀的长度。代码如下

  1. public String longestCommonPrefix(String[] strs) {
  2. if(strs.length == 0)
  3. return "";
  4. if(strs == null ) {
  5. return null;
  6. }
  7. if(strs.length == 1) {
  8. return strs[0];
  9. }
  10. int minLength = Integer.MAX_VALUE;
  11. for (int i = 0; i < strs.length; i++) {
  12. if(minLength > strs[i].length()) {
  13. minLength = strs[i].length();
  14. }
  15. }
  16. if(minLength == 0)
  17. return "";
  18. int[] commons = new int[strs.length-1];
  19. for (int i = 0; i < strs.length-1; i++) {
  20. for (int j = 0; j < minLength; j++) {
  21. if(strs[i].charAt(j) == strs[i+1].charAt(j)) {
  22. commons[i]++;
  23. }else
  24. break;
  25. }
  26. }
  27. int longestCommonPrefix = Integer.MAX_VALUE;
  28. for(int i=0; i<commons.length; i++) {
  29. if(longestCommonPrefix > commons[i]) {
  30. longestCommonPrefix = commons[i];
  31. }
  32. }
  33. return strs[0].substring(0, longestCommonPrefix);
  34. }

    程序用时9ms,然后看到前面有个用时6ms的代码,研究一番觉得甚是巧妙 ,现在贴出来供诸君欣赏

  1. public static String longestCommonPrefix(String[] strs) {
  2. int count = strs.length;
  3. String prefix = "";
  4. if(count != 0){
  5. prefix = strs[0];
  6. }
  7. for(int i=0; i<count; i++){
  8. //关键代码,不断的从后往前截取字符串,然后与之相比,直到startsWith()返回true
  9. while(!strs[i].startsWith(prefix)){
  10. prefix = prefix.substring(0, prefix.length()-1);
  11. }
  12. }
  13. return prefix;
  14. }

    代码巧妙的利用了java提供的函数,几乎是不费一兵一卒就拿下了这道题目。非常佩服[鼓掌!鼓掌]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/727639
推荐阅读
相关标签
  

闽ICP备14008679号