zoukankan      html  css  js  c++  java
  • [LeetCode]-011-Longest Common Prefix

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

    []
    =>""
    ["abcweed","htgdabc","sabcrf"]
    =>""
    ["abcweed","abhtgdc","abacrf"]
    =>"ab"

    题目大意:求字符串数组的最长子前缀

     1 public class Solution{
     2     public String longestCommonPrefix(String[] strs) {
     3         //System.out.println(Arrays.toString(strs));
     4         if(strs.length == 0)
     5             return "";
     6         int min = Integer.MAX_VALUE;
     7         for(String s : strs){
     8             if(min>s.length())
     9                 min = s.length();
    10         }
    11         if(min==0)
    12             return "";
    13         //System.out.println(min);
    14         String prefix = "", tmp = "";
    15         int i=0;
    16         for( ; i<min; i++){
    17             prefix = strs[0].substring(0,(i+1));
    18             //System.out.println("prefix=" + prefix);
    19             for(int j=1; j<strs.length; j++){
    20                 tmp = strs[j].substring(0,(i+1));
    21                 //System.out.println("tmp=" + tmp);
    22                 if(!prefix.equals(tmp))
    23                     return strs[0].substring(0,(i));
    24             }
    25         }
    26         System.out.println("i=" + strs[0].substring(0,(i)));
    27         return "";
    28     }
    29     
    30     
    31     public static void main(String[] args){
    32         String[] arr = {"","asdffg","aswd"};
    33         if(args.length!=0)
    34             arr = args;
    35         Solution solution = new Solution();
    36         String res = solution.longestCommonPrefix(arr);
    37         System.out.println(res);
    38     }
    39 }
  • 相关阅读:
    hdu5728 PowMod
    CF1156E Special Segments of Permutation
    CF1182E Product Oriented Recurrence
    CF1082E Increasing Frequency
    CF623B Array GCD
    CF1168B Good Triple
    CF1175E Minimal Segment Cover
    php 正则
    windows 下安装composer
    windows apache "The requested operation has failed" 启动失败
  • 原文地址:https://www.cnblogs.com/lianliang/p/5403634.html
Copyright © 2011-2022 走看看