[LeetCode]014. Longest Common Prefix

本文介绍了一种寻找字符串数组中最长公共前缀的方法,并提供了Java和Python两种实现方案。通过对比字符串的第一个字符来逐步确定公共前缀,最终返回结果。

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


Solutions:

use the first string as the comparison.

compare the first character of all the strings, if are all the same, then to next...

if there is difference, break the loop.

Running Time: O(n*n);

Pass OJ: 580ms


注意以下代码中的注释,使用

strs[i].length() == k

当某string的长度等于k时,其能取到的index只能为k-1, 此时无法比较,因而break。



public class Solution {
    public String longestCommonPrefix(String[] strs) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int len = strs.length;
        String result = "";
        if(len == 0 || strs[0].length() == 0){
            return "";
            //The OJ requires return "" here.
        }
        int k = 0;
        while(k<strs[0].length()){
            int i = 0;
            char val = ' ';
            //use one white space for initialize the char val;
            
            for(i=0; i<len; i++){
                if(i==0){
                    val = strs[0].charAt(k);
                }
                if(strs[i].length() == k || val != strs[i].charAt(k)){
                    break;
                    // use the k here which can eliminate not only the null strings 
                    // but also the strings whose size are equal to k.
                }
            }
            
            // use for detecting whether all chars(till the end) are eaual.
            if(i != len){
                break;
            }
            result += val;
            k++;
        }
        return result;
    }
}


2015-04-17 update python solution:

<pre name="code" class="python">class Solution:
    # @param strs, a string[]
    # @return a string
    def longestCommonPrefix(self, strs):
        length_strs = len(strs)
        if length_strs == 0:
            return ""
        prefix = ""
        for i in range(len(strs[0])):
            #print '\n%d:\n'%i
            j = 0
            while j < length_strs:
                if j == 0:
                    val = strs[0][i]
                #print j
                if len(strs[j]) == len(prefix) or strs[j][i] != val:
                    break
                j += 1
            if j != length_strs:
                break
            prefix += val
        return prefix



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值