Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80428
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-02-04 09:43:04

题目:Write a function to find the longest common prefix string amongst an array of strings.
分析:典型题目。LCP问题,即找出字符串数组中最大公共前缀。思路为先找出前两个字符串的公共前缀,再找出该公共前缀与下一个字符串的公共前缀,以此类推,直到找出所有字符串的公共前缀。程序如下:

点击(此处)折叠或打开

  1. public class Solution {
  2.     public String longestCommonPrefix(String[] strs) {
  3.         int arrlen = strs.length;
  4.         String result = new String();
  5.         if(arrlen == 0){
  6.             return result;
  7.         }
  8.         result = strs[0];
  9.         for(int i = 1; i < arrlen; i++){
  10.             result = findCommonPrefix(result,strs[i]);
  11.         }
  12.         return result;
  13.     }
  14.     
  15.     public String findCommonPrefix(String str1,String str2){
  16.         char[] charr1 = str1.toCharArray();
  17.         char[] charr2 = str2.toCharArray();
  18.         StringBuilder resultsb = new StringBuilder();
  19.         int i = 0;
  20.         int str1len = str1.length();
  21.         int str2len = str2.length();
  22.         while(i < str1len && i < str2len && charr1[i] == charr2[i]){
  23.             i++;
  24.         }
  25.         for(int j = 0; j < i; j++){
  26.             resultsb.append(charr1[j]);
  27.         }
  28.         return resultsb.toString();
  29.     }
  30. }

                                                                                                                                                                                                                                                                            
阅读(1060) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~