LeetCode 14. Longest Common Prefix 最长公共前缀

题目

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

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

讲解

首先,我们初始化一个叫”longestCommonPrefix”字符串的变量,就使用输入数列中第一个字符串的值。 接着通过比较这个”longestCommonPrefix”和数列中其他字符串,找到对于整个数列中字符串来讲最长的公共前缀。

视频教学

Java参考代码

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        String longestCommonPrefix = strs[0];
        
        for (int i = 1; i < strs.length; i++) {
            int j = 0;
            String currentString = strs[i];
            
            while (j < longestCommonPrefix.length() && j < currentString.length() && longestCommonPrefix.charAt(j) == currentString.charAt(j)) {
                j++;
            }
            
            if (j == 0) {
                return "";
            }
            
            longestCommonPrefix = longestCommonPrefix.substring(0, j);
        }
        
        return longestCommonPrefix;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注