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.

  • 相关阅读:
    bzoj 1188 [HNOI2007]分裂游戏(SG函数,博弈)
    poj 3710 Christmas Game(树上的删边游戏)
    poj 1704 Georgia and Bob(阶梯博弈)
    110 最小路径和
    109 数字三角形
    63 搜索旋转排序数组II
    62 搜索旋转排序数组
    61 搜索区间
    58 四数之和
    关于初始值的问题
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086472.html
Copyright © 2011-2022 走看看