题目

最长公共前缀

给k个字符串,求出他们的最长公共前缀(LCP)

样例

在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"

在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

解题

思路:

1.找到最短的字符串,求出长度shortest

2.设最短公共前缀是shortest

3.遍历所有字符串,比较长度是shortest的前缀是否相同,相同就是答案

3.不相同shortest-=1 重复 2 、3 步

Java

public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
HashMap<Character,Integer> map= new HashMap<Character,Integer>();
if(strs.length ==0)
return "";
int len = strs.length;
int shortest = Integer.MAX_VALUE;
for(int i=0;i<len;i++){
int tmplen = strs[i].length();
shortest = Math.min(shortest,tmplen);
}
int i =0;
while(shortest>0){
for( i=0;i<len-1;i++){
String str1 = strs[i].substring(0,shortest);
String str2 = strs[i+1].substring(0,shortest);
if( str1.equals(str2))
continue;
else
break;
}
if(i==len-1)
break;
else
shortest--;
}
return strs[0].substring(0,shortest); }
}

Java Code

既然可以倒着走,也可以正着走

public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
if(strs.length ==0)
return "";
if(strs.length == 1)
return strs[0];
int len = strs.length;
int shortest = 1;
boolean flag = false;
int i =0;
while(!flag){
for( i=0;i<len-1;i++){
if(strs[i].length() < shortest|| strs[i+1].length() < shortest){
flag = true;
break;
}
String str1 = strs[i].substring(0,shortest);
String str2 = strs[i+1].substring(0,shortest);
if( str1.equals(str2))
continue;
else
break;
}
if(i==len-1)
shortest++;
else{
flag= true;
} }
return strs[0].substring(0,shortest-1); }
}

Java Code

正着走就没有比较字符串,直接比较对应字符是否相等就好了

public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
if(strs.length ==0)
return "";
if(strs.length == 1)
return strs[0];
int len = strs.length;
int shortest = 0;
boolean flag = false;
int i =0;
while(!flag){
for( i=0;i<len-1;i++){
if(strs[i].length() <= shortest|| strs[i+1].length() <= shortest){
flag = true;
break;
}
char ch1 = strs[i].charAt(shortest);
char ch2 = strs[i+1].charAt(shortest);
if( ch1== ch2)
continue;
else
break;
}
if(i==len-1)
shortest++;
else{
flag= true;
} }
return strs[0].substring(0,shortest); }
}

Java Code

可能会发现三个返回结果为什么不一样?

1.逆着找,取子串的方式是  substring(start,end)  取得是从start 到 end -1 位置内的字符,这里的shortest就相当于end 在最后比较结束的时候 shortest 是当前比较结束的位置,这个end位置内的前缀都一样

所以返回的是substring(0,shortest) 取得字符是:0 到shortest -1的部分

2.正着找,跳出循环的是 第一个不满足条件的shortest ,取子串的方式也是  substring(start,end) 需要进行shortest - 1

3.比较字符,跳出循环的shortest是最长子串的后一个位置,可以直接用substring(0,shortest) 返回结果的

lintcode :最长公共前缀的更多相关文章

  1. lintcode-78-最长公共前缀

    78-最长公共前缀 给k个字符串,求出他们的最长公共前缀(LCP) 样例 在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 ...

  2. [转][LeetCode]Longest Common Prefix ——求字符串的最长公共前缀

    题记: 这道题不难但是很有意思,有两种解题思路,可以说一种是横向扫描,一种是纵向扫描. 横向扫描:遍历所有字符串,每次跟当前得出的最长公共前缀串进行对比,不断修正,最后得出最长公共前缀串. 纵向扫描: ...

  3. LeetCode Longest Common Prefix 最长公共前缀

    题意:给多个字符串,返回这些字符串的最长公共前缀. 思路:直接逐个统计同一个位置上的字符有多少种,如果只有1种,那么就是该位是相同的,进入下一位比较.否则终止比较,返回前缀.可能有一个字符串会比较短, ...

  4. 扩展KMP--求字符串S的所有后缀和字符串T的最长公共前缀

    在解上面这个问题前我们要先解决一个类似的问题:求字符串s的所有后缀和s本身的最长公共前缀: 我们用next[]数组保存这些值: 现在我们假设要求next[ x ],并且next[ i ] 0<i ...

  5. BNUOJ34990--Justice String (exkmp求最长公共前缀)

    Justice String Given two strings A and B, your task is to find a substring of A called justice strin ...

  6. [Swift]LeetCode14. 最长公共前缀 | Longest Common Prefix

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

  7. [LeeCode]14. 最长公共前缀

    题目链接:https://leetcode-cn.com/problems/longest-common-prefix/ 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀 ...

  8. python(leetcode)-14最长公共前缀

    编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...

  9. leetcode-14最长公共前缀

    leetcode-14最长公共前缀 题目 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower& ...

随机推荐

  1. 关于UIView需要看的一些官方文档

    View Controller PG(Programming Guide)  看过一遍 View PG 正在看 Drawing and Printing PG Quartz 2D PG 更高级的cus ...

  2. SQL-LINQ-Lambda语法对照,好记性不如烂笔头

    忘记的时候就翻阅翻阅吧~~ SQL LINQ Lambda SELECT *FROM HumanResources.Employee from e in Employees select e Empl ...

  3. shell操作文件的几条命令:删除最后一列、删除第一行、diff等

    删除文件第一行: sed '1d' filename 删除文件最后一列: awk '{print $NF}' filename awk删除重复行的命令:awk '{if (!seen[$0]++) { ...

  4. SQL Server 2008 的安装

    SQL Server 2008简体中文企业版下载(SQL2008) SQL Server 2008分为SQL Server 2008企业版.标准版.工作组版.Web版.开发者版.Express版.Co ...

  5. 静态数据认证(SDA)与动态数据认证(DDA)的区别

    PBOC/EMV里有两个非常重要的概念,SDA(staticdataauthentication)和DDA(dynamicdataauthentication),分别叫做静态数据认证和动态数据认证.这 ...

  6. Implementation Documentation[转]

    原文地址:http://prasanna-adf.blogspot.tw/2009/04/implementation-documentation.html Following are the lis ...

  7. Javascript Date Format

    // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...

  8. 使用NPOI和线程池快速加载EXCEL数据

    private void FilterData() { List<Task> tasks = new List<Task>(); IWorkbook workbook = Cs ...

  9. Build Simple HTTP server

    1. The server just support POST&PUT method 2. It is a Python server, and save upload files in sp ...

  10. [geeksforgeeks] Bottom View of a Binary Tree

    http://www.geeksforgeeks.org/bottom-view-binary-tree/ Bottom View of a Binary Tree Given a Binary Tr ...