leetcode--Longest Common Prefix

本文介绍了一种寻找字符串数组中最长公共前缀的方法,并提供了一个Java实现示例。该算法首先确定最短字符串长度,然后逐字符比较所有字符串直至找到不匹配的位置。

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

[java]  view plain  copy
  1. public class Solution {  
  2.     public String longestCommonPrefix(String[] strs) {  
  3.         if(strs.length==0return "";         
  4.         boolean same = true;  
  5.         int minLen = 900000;          
  6.         for(int i=0;i<strs.length;i++){  
  7.             if(strs[i].length()<minLen) minLen = strs[i].length();  
  8.         }  
  9.         int index = 0;        
  10.         while(index<minLen){   
  11.             same = true;  
  12.             for(int i=0;i<strs.length-1;i++){                  
  13.                 if(strs[i].charAt(index)!=strs[i+1].charAt(index)){   
  14.                     same = false;  
  15.                     break;  
  16.                 }  
  17.             }             
  18.             if(same) index++;  
  19.             else break;  
  20.         }                 
  21.         if(minLen==0return "";  
  22.         else{             
  23.             return strs[0].substring(0,index);  
  24.         }  
  25.     }  
  26. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/45495683

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值