LeetCode:14. Longest Commen Prefix(Easy)

1. 原题链接

https://leetcode.com/problems/longest-common-prefix/description/

2. 题目要求

   给定一个字符串数组,让你求出该数组中所有字符串的最大公共前缀。例如{"qqwwee", "qqww", "qqfds"}的最大公共前缀为"qq",{"qqwwee", "qqww", "qqfds", "wea"}的最大公共前缀为""(空)。

3. 解题思路

(1)首先判断该字符串数组长度是否为零,为零直接返回最大公共前缀为空;

(2)假设该字符串数组中第一个元素strs[0]为最大公共前缀,然后与第二个元素进行比较,判定第二个元素是否包含假定的最大公共前缀,且假定的最大公共前缀的起始位置为0。满足以上要求,则证明该元素与之前的元素共同拥有该前缀。如果不包含,则证明假定的公共前缀不符合要求,将假定的公共前缀缩短一位,然后重新比较。

4. 代码实现

 1 public class LongestCommenPrefix14 {
 2 
 3     public static void main(String[] args) {
 4         String[] strs = {"weeer", "weer", "wer"};
 5         System.out.println(LongestCommenPrefix14.longestCommonPrefix(strs));
 6     }
 7 
 8     public static String longestCommonPrefix(String[] strs) {
 9         if (strs.length == 0)
10             return "";
11         String prefix = strs[0];
12         for (int i = 1; i < strs.length; i++) {
13             while (strs[i].indexOf(prefix) != 0) {   //与假定的公共前缀不匹配
14                 prefix = prefix.substring(0, prefix.length() - 1); //缩短假定的公共前缀
15                 if (prefix.equals(""))
16                     return "";
17             }
18         }
19         return prefix;
20     }
21 }
原文地址:https://www.cnblogs.com/huiAlex/p/8072229.html