LintCode 78:Longest Common Prefix
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 "";
}
String prefix = strs[0];
int i = 0;
int j = 0;
for ( i=1;i<strs.length;i++){
if(strs[i].length() == 0){
return "";
}
for( j=0;j<prefix.length();j++){
if(strs[i].charAt(j) != prefix.charAt(j)){
prefix = prefix.substring(0,j);
}
}
}
return prefix;
}
}
思路:
默认数组第一个是prefix,然后循环比较数组中的每一个字符串,直到不相等,返回substring即可,返回的substring一定是最长的公共前缀。
注:判断数组为空或者数组中有空字符串
时间复杂度:O(第一个字符串长度^2),java耗时1563 ms。
LintCode 78:Longest Common Prefix的更多相关文章
- 78. Longest Common Prefix【medium】
Given k strings, find the longest common prefix (LCP). Example For strings "ABCD", " ...
- [LintCode] Longest Common Prefix 最长共同前缀
Given k strings, find the longest common prefix (LCP). Have you met this question in a real intervie ...
- [LeetCode] Longest Common Prefix 最长共同前缀
Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...
- 【leetcode】Longest Common Prefix
题目简述: Write a function to find the longest common prefix string amongst an array of strings. 解题思路: c ...
- 14. Longest Common Prefix
题目: Write a function to find the longest common prefix string amongst an array of strings. Subscribe ...
- Leetcode Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings. class Solutio ...
- [LeetCode] 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings. public class ...
- No.014:Longest Common Prefix
问题: Write a function to find the longest common prefix string amongst an array of strings. 官方难度: Eas ...
- 68. Longest Common Prefix
Longest Common Prefix Write a function to find the longest common prefix string amongst an array of ...
随机推荐
- 初次启动app校验的活动图和分析
初次启动活动图 version 1 version 2 version 3 根据上图的活动图分析,可能存在较严重的问题: 主线程中如果发现是sdcard的url,则可能进行重命名 FirstEnter ...
- 用ip来获得用户所在地区信息
淘宝api: package com.ebways.mq.utils; import com.alibaba.fastjson.JSON; import com.ebways.common.utils ...
- 企业号查询部门id(改版后)
1.搜索部门,输入"名称" 2.在后面可以查到部门ID
- 通过挂载系统光盘搭建本地yum仓库的方法
在CentOS系统中,我们常常会安装大量的软件,但许多软件包都存在需要依赖性,当然我们可以通过一一安装依赖包来完成安装,但对于有些软件包需要大量的依赖包,再一一安装起来会显得特别麻烦.接下来我们就来讲 ...
- js创建命名空间
CreateNameSpace: function () { var nameSpaceObjec = arguments[0].split('.'); var currentNameSpaceNam ...
- Jquery获取select选中的文本与值
jquery获取select选择的文本与值获取select :获取select 选中的 text : $("#ddlregtype").find("option:s ...
- 【python】发送post请求
1. json格式的post请求 关键部分加粗显示了,主要是post数据的编码方式以及请求头的Content-type #coding=utf8 import json import gzip imp ...
- POJ 2352 Stars 线段树
题目链接 题意:在一个二维平面上有n个星星,每个星星的等级为x,x为该星星左方和下方所包含的星星的数量(包含正左和正下的),输出每个等级各有多少星星,星星坐标按照y序递增给出,y值相同按照x递增给出. ...
- 解决VMware虚拟机宿主机与虚拟机通讯慢
本地连接--> 属性 --> 配置(C) -->高级 页面的属性框中找到"Large Send Offload"(中文名称叫:大量传送减负)==>Disab ...
- libsvm数据处理初略流程