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