美文网首页
LeetCode每日一题:longest common pref

LeetCode每日一题:longest common pref

作者: yoshino | 来源:发表于2017-07-05 15:45 被阅读38次

    问题描述

    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 pref

          本文链接:https://www.haomeiwen.com/subject/xheqhxtx.html