zoukankan      html  css  js  c++  java
  • LeetCode 题目十四

    我的解答

    public String longestCommonPrefix(String[] strs) {
    
            String longestCommonPrefix = "";
            for (int j = 0; j < strs.length; j++) {
    
                if (j == 0) {
                    longestCommonPrefix = strs[j];
                    continue;
                }
                if (longestCommonPrefix.length() > strs[j].length()) {
                    longestCommonPrefix = strs[j];
                }
    
            }
    
            if (longestCommonPrefix.length() == 0) return "";
            longestCommonPrefix = strs[0].substring(0, longestCommonPrefix.length());
            for (String string : strs) {
                String perfix = string;
                if (longestCommonPrefix.length() <= string.length()){
                    perfix = string.substring(0, longestCommonPrefix.length());
                }
                if (longestCommonPrefix.equals(perfix)) {
                    continue;
                } else {
                    while (!longestCommonPrefix.equals(perfix)) {
                        int length = longestCommonPrefix.length();
                        if (longestCommonPrefix.length() == 1) {
                            perfix = perfix.substring(0, 1);
                            longestCommonPrefix = longestCommonPrefix.substring(0, 1);
                            if (!perfix.equals(longestCommonPrefix)) {
                                longestCommonPrefix = "";
                            }
                            break;
                        } else {
                            perfix = perfix.substring(0, length - 1);
                            longestCommonPrefix = longestCommonPrefix.substring(0, length - 1);
                        }
    
                    }
                }
    
            }
    
            return longestCommonPrefix;
        }
  • 相关阅读:
    输入流输出流打印到文件
    前缀和
    树形dp
    快速幂 ,快速幂优化,矩形快速幂(java)
    尾递归
    java中bigInteger的应用
    求树的最大直径
    买不到的数目
    ccpc 长春站 G
    大学ACM第二周心得
  • 原文地址:https://www.cnblogs.com/zhangqian27/p/10971213.html
Copyright © 2011-2022 走看看