zoukankan      html  css  js  c++  java
  • [Leetcode 18] 14 Longest Common Prefix

    Problem:

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

    Analysis:

    Each time take a character from the first string and compare it with other strings' same position character.

    If reaching some end of some string or find a mismatch, then the longest common prefix has been found, just return.

    Take some corner cases into considerations([], [""]).

    Time Complexity O(n*m), n is the strings in the given input, m is the prefix compared when existing. The worst case for m is length of the shortest string in the array.

    Space Complexity O(l), l is the total characters in the String array.

    Code:

     1 public class Solution {
     2     public String longestCommonPrefix(String[] strs) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if (strs.length == 0 || strs[0].length() == 0)
     6             return "";
     7             
     8         int pos = 0;
     9         char ch = 'c';
    10         String s0 = strs[0];
    11         while (true) {
    12             if (pos == s0.length())
    13                 return s0.substring(0, pos);
    14             
    15             ch = s0.charAt(pos);
    16             for (String s : strs) {
    17                 if (pos == s.length() || ch!=s.charAt(pos))
    18                     return s0.substring(0, pos);
    19             }
    20             
    21             pos += 1;
    22         }
    23     }
    24 }
    View Code

    Attention:

    Don't know why in JudgeLarge, sometimes will have Time Limit Exceeded error but sometimes will AC. May be problems in testing environment.

  • 相关阅读:
    关于oracle当中数据类型转换的问题
    CASE WHEN的两种格式
    C#设置默认打印机
    运用Merge Into实现增加或更新数据
    增加或修改的存储过程
    深拷贝与浅拷贝
    sql server两种分页方法
    获取sql执行时间
    inserted触发器,一张表插入数据时,同时向另外一张表插入数据
    List<string[]> 如何去重
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086472.html
Copyright © 2011-2022 走看看