14. Longest Common Prefix

题目:

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

链接:http://leetcode.com/problems/longest-common-prefix/

题解:

求最长前缀。按列计算,判断条件是当前列字符是否相同,以及当前行的长度是否有效。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public String longestCommonPrefix(String[] strs) {

        if(strs == null || strs.length == 0)

            return "";

        

        for(int j = 0; j < strs[0].length(); j ++)                  // calc in each row

            for(int i = 1; i < strs.length; i ++)                   // calc in each column

                if(j == strs[i].length() || strs[0].charAt(j) != strs[i].charAt(j))

                    return  strs[0].substring(0, j);

                    

        return strs[0];

    }

}

 

测试:

Reference:

你可能感兴趣的:(long)