zoukankan      html  css  js  c++  java
  • [leetcode]Longest Common Prefix

    Longest Common Prefix

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

    算法思路:

    思路:貌似木有什么捷径,逐个比较,遇到不同即断开。

    代码如下:

     1 public class Solution {
     2     public String longestCommonPrefix(String[] strs) {
     3         if(strs == null || strs.length == 0) return "";
     4         StringBuilder sb = new StringBuilder();
     5         int shortestLength = Integer.MAX_VALUE; 
     6         for(String s : strs){
     7             shortestLength = Math.min(shortestLength,s.length());
     8         }
     9         breakable:
    10         for(int i = 0; i < shortestLength; i++){
    11             char c = strs[0].charAt(i);
    12             for(String s : strs){
    13                 if(s.charAt(i) != c){
    14                     break breakable;
    15                 }
    16             }
    17             sb.append(c);
    18         }
    19         return sb.toString();
    20     }
    21 }
  • 相关阅读:
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    洛谷
    GXU
  • 原文地址:https://www.cnblogs.com/huntfor/p/3883651.html
Copyright © 2011-2022 走看看