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 }
  • 相关阅读:
    Spring MVC的常用注解(一)
    Spring MVC接口实例
    MVC模式和Spring MVC初识
    Hbase数据结构和shell操作
    Hbase的安装和配置
    ZooKeeper安装、配置和使用
    hadoop的安装和配置
    VMware Workstation安装CentOS 7和开发环境
    Java基础-内部类
    SSM三大框架整合
  • 原文地址:https://www.cnblogs.com/lianliang/p/5403634.html
Copyright © 2011-2022 走看看