[LeetCode]014. Longest Common Prefix

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


 
 

你可能感兴趣的:(java,LeetCode,python)