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.

  • 相关阅读:
    团队项目:二次开发1.0
    文法分析2
    文法分析1
    词法分析实验总结
    0916 编程实验一 词法分析程序
    0909初学编译原理
    复利计算
    0302思考并回答一些问题
    1231 实验四 递归下降语法分析程序设计
    1118实验三有限自动机构造与识别
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086472.html
Copyright © 2011-2022 走看看