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.

  • 相关阅读:
    CSS 之 div中文字超出时自动换行
    架构设计分享之权限系统(看图说话)
    perl杂项
    nginx比较apache
    Apache与Nginx的优缺点比较
    DVB系统中PCR的生成和PCR校正
    相关软件测试工具
    我遇到的有趣面试题:破解程序
    OpenStack 部署运维实战
    一些大公司的开源项目及代码托管平台
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086472.html
Copyright © 2011-2022 走看看