• leetcode——14. 最长公共前缀


    class Solution:
        def longestCommonPrefix(self, strs: List[str]) -> str:
            s=''
            if strs==[] :
                return ''
            if '' in strs:
                return ''
            for i in range(len(strs[0])):
                for j in range(1,len(strs)):
                    if i<len(strs[j]) and strs[j][i]!=strs[0][i]:
                        return s
                    if i==len(strs[j]):
                        return s
                s+=strs[0][i]
            return s
    执行用时 :44 ms, 在所有 python3 提交中击败了89.44%的用户
    内存消耗 :13.7 MB, 在所有 python3 提交中击败了5.53%的用户
     
                                                              ——2019.10.17
     

    两两依次对比之后得到结果
    public String longestCommonPrefix(String[] strs) {  //最长公共前缀,要首先找出长度最小的字符串,然后进行比较;
            //或者是依次进行比较,更新最短长度,
            int n = strs.length;
            if(n == 0){
                return "";
            }
            if(n ==1){
                return strs[0];
            }
            String st = strs[0];
            if(st.equals("")){
                return "";
            }
            int maxLen = Integer.MAX_VALUE;
            for(int i = 1;i<n;i++){
                int m1 = Math.min(strs[i].length(),strs[i-1].length());
                int j = 0;
                for(;j<m1;j++){
                    if(strs[i].equals(strs[i - 1])){
                        maxLen = Math.min(maxLen,m1);
                    }else if(strs[i].charAt(j) != strs[i-1].charAt(j)){
                        maxLen = Math.min(maxLen,j);
                    }
                }
                if(j == m1){
                    maxLen = Math.min(maxLen,j);
                }
            }
            return strs[0].substring(0,maxLen);
        }

    看了别人如下的答案,简直绝妙啊

    public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            String prex = strs[0];
            for(String str : strs) {
                while(str.indexOf(prex) != 0) {
                    prex = prex.substring(0, prex.length() -1);
                }
            }
            return prex;
        }

    ——2020.7.7

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    https 证书
    js 压缩
    身份证认证
    在 Visual Studio 2015 中关闭系统级的 Runtime Exceptions
    在 Visual Studio 2015 中关闭 Browser Link
    List<T>.ForEach()的使用
    使用Microsoft.Practices.EnterpriseLibrary.Validation.dll验证类成员
    jQuery.filter()的强大功能
    jQuery Checkbox Selected
    Get SQL String From Query Object In Entity Framework
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11698013.html
Copyright © 2020-2023  润新知