14. Longest Common Prefix

一、题目

  1、审题

    

   2、分析

    求出字符串素组的最长共同前缀。

二、解答

  1、分析:

   方法一:

    a、求出数组中长度最短的字符串作为临时共同前缀;

    b、遍历字符串数组,判断每一个元素是否拥有临时前缀

      Y: 返回临时前缀

      N:c

    c、临时前缀减去最后一个字符,进行 b;

  

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        if(strs.length == 0)
            return "";
        String shortist = strs[0];
        for (int i = 1; i < strs.length; i++) {
            if(strs[i].length() < shortist.length())
                shortist = strs[i];
        }
        while (shortist.length() > 0) {
            int i = 0;
            for ( ; i < strs.length; i++) {
                if(!strs[i].startsWith(shortist))
                    break;
            }
            if(i == strs.length)
                return shortist;
            else
                shortist = shortist.substring(0, shortist.length() - 1);
        }

        return shortist;
    }
}

  方法二:

    a、将第一个元素作为临时前缀,与第二个元素比较,得出前两个元素的共同最长前缀;

    b、将 a 所得的前缀与后一个个元素比较,得出前三个元素最长共同前缀;

    c、重复 b

    

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0) return  "";
        int i = 1;
        String prefix = strs[0];
        while (i < strs.length) {
            while (strs[i].indexOf(prefix) != 0)
                prefix = prefix.substring(0, prefix.length() - 1);
            i++;
        }
        return  prefix;
    }

}
原文地址:https://www.cnblogs.com/skillking/p/9405234.html