博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】Longest Common Prefix
阅读量:7282 次
发布时间:2019-06-30

本文共 810 字,大约阅读时间需要 2 分钟。

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

 

这题的意思是,求字符串数组中的所有字符串的公共头。

解题思路:由于要求所有字符串的公共头,和求几个整数的公约数一样。我们先将字符串数组中的相邻元素进行比较,取出相同的部分,放入一个TreeMap中,其中TreeMap的key为相同部分字符串的长度,值为相同部分的字符串。最后取出最小的key即可。

class Solution {    public String longestCommonPrefix(String[] strs) {         int len=strs.length;        if(len==0)            return "";        if(len==1)            return strs[0];        TreeMap
topMap=new TreeMap
(); for(int i=1;i
str2.length()) { num=str2.length(); } else { num=str1.length(); } String top=""; //两个字符串相同的部分 for(int j=0;j

 

转载于:https://www.cnblogs.com/contixue/p/7827417.html

你可能感兴趣的文章
实验三 编程、编译、连接、跟踪
查看>>
构建之法第一章
查看>>
进制之间的互相转换,进制的原码,反码,补码
查看>>
Tomcat02
查看>>
SQL Server 添加描述
查看>>
locust===Writing a locustfile
查看>>
生产者消费者模式
查看>>
oracle学习篇五:组函数,分组统计
查看>>
PHP-Manual的学习----【语言参考】----【类型】-----【NULL】
查看>>
Colorable Fantasy UI
查看>>
C# Reflection BindingFlags
查看>>
NGUI3.x Button事件
查看>>
FFmpeg 官方 20160227 之后 追加 libmfx 无法在 xp 上运行的解决方法
查看>>
多线程的使用注意点
查看>>
【GitHub】README.md文件中 markdown语法 插入超链接
查看>>
移动着,心就变了
查看>>
2014冬去春来
查看>>
Python全栈--6.1-match-search-findall-group(s)的区别以及计算器实例
查看>>
基本概念
查看>>
《Linux内核设计与实现》读书笔记(10)--- 定时器和时间管理(2)
查看>>