LeetCode(14):最长公共前缀 Longest Common Prefix(Java)

本文介绍了求解LeetCode第14题"最长公共前缀"的多种方法,包括水平扫描法、垂直扫描法、分治算法结合水平/垂直扫描以及二分查找法,并提供了相关拓展,如使用前缀树解决字符串键值的最长公共前缀问题。同时,强调了此类问题在程序员笔试中的重要性。
摘要由CSDN通过智能技术生成

2019.5.5 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

求多个字符串的最长公共前缀,可以有以下几种方法:

1.水平扫描法

通过在线处理,不断调整公共前缀的长度。将第一个字符串的长度定义为初始最长公共前缀,将每个新串与最长前缀比对并更新最长前缀长度。

2.垂直扫描法:

按列扫描,简单粗暴,依次验证所有字符串的第i个元素即可。

3.分治算法+水平扫描法/垂直扫描法

通过分治算法将字符串两两比较获得公共前缀。

4.二分查找算法(配合startsWith方法)

通过二分查找算法定位字符串最长公共前缀点,需要配合String类的startsWith方法。

另外,对字符串前缀问题有以下拓展:

如果给定一些键值字符串S=[S1……Sn],需要找到字符串q与S的最长公共前缀,可以利用前缀树/字典树(Prefix Tree),具体题目和实现参考:LeetCode(208):实现 Trie (前缀树) Implement Trie (Prefix Tree)(Java)


传送门:最长公共前缀

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

If there is no common prefix, return an empty string “”.

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:
输入: ["flower","flow","flight"]
输出: "fl"

示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:
所有输入只包含小写字母 a-z 。


/**
 * 
 * @author ChopinXBP
 * Write a function to find the longest common prefix string amongst an array of strings.
 * If there is no common prefix, return an empty string "".
 * Note: All given inputs are in lowercase letters a-z.
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀,返回空字符串 ""。
 * 说明: 所有输入只包含小写字母 a-z 。
 *
 */

public class LongestCommonPrefix {
   

	public static void main(String[] args) {
   
		// TODO Auto-generated method stub
		String[] strs = {
   "flower","flow","flight"};
		String[] strs2 = {
   "aa","aa"};
		String[] strs3 = {
   "a"};
		System.out.println(longestCommonPrefix(strs));
		System.out.println(longestCommonPrefix2(strs));
		System.out.println(longestCommonPrefix3(strs));
		System.out.println(longestCommonPrefix4(strs));
		System.out.println(longestCommonPrefix4(strs2));
		System.out.println(longestComm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值