LeetCode每日一题:longest common prefix

问题描述

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

问题分析

这道题本来想用动态规划来做的,但是直接暴力求解也很方便,因为最长公共前缀的距离肯定是越来越短的,直接一一比较过去即可。

代码实现

public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int j = 0;
            String preFix = "";
            while (j < result.length() && j < strs[i].length() && result.charAt(j) == strs[i].charAt(j)) {
                preFix = preFix + strs[i].charAt(j);
                j++;
            }
            result = preFix;
        }
        return result;
    }

你可能感兴趣的:(LeetCode每日一题:longest common prefix)