• LeetCode--Longest Common Prefix


    Write a function to find the longest common prefix string amongst an array of strings.

    找出所有字符串的最长公共前缀.

    思路:首先比较前两个字符串的公共部分,将其公共部分放到prefix中,然后再拿prefix和第三个比较得到新的prefix,如此循环即可,当比较的两个字符不相同是则跳出循环。

    public class LongestCommonPrefix {
      public static void main(String[] args) {
      String[] strs = {"hello","hello","hel"};
      String prefix = strs[0];
      for(int i = 1; i < strs.length; ++i){
        prefix = findCommonLongestPrefix(prefix,strs[i]);
      }
      System.out.println(prefix);
    }

    public static String findCommonLongestPrefix(String prefix, String current) {
      StringBuffer sb = new StringBuffer();
      int len = prefix.length() > current.length() ? current.length() : prefix.length();
      for(int i = 0; i < len; ++i){
        if(prefix.charAt(i) == current.charAt(i)){
          sb.append(prefix.charAt(i));
        }else{
          break;
        }
      }
      return sb.toString();
      }
    }

  • 相关阅读:
    2016 年末 QBXT 入学测试
    Codevs 3409 搬礼物
    寻找子串位置
    Balanced Lineup
    统计难题
    爱在心中
    传话
    火柴排队
    新斯诺克
    排序
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6477936.html
Copyright © 2020-2023  润新知