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();
  }
}

IT文库 » LeetCode–Longest Common Prefix
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址