leetcode 14. Longest Common Prefix
2016-05-04 09:46
483 查看
//Write a function to find the longest common prefix string amongst an array of strings. public class Solution { public static void main(String[] args) { String[] a = {"qweaqw","qweazxc","qweaz"}; String result = find(a); System.out.println(result); } public static String find(String[] strs) { String result = ""; boolean flag = true; if(strs.length == 0){ //若输入空数组,则返回空串 return ""; } int length = strs[0].length(); for(int i = 1;i<strs.length;i++){ //确定字符串数组中长度最小的字符串长度 if(length>strs[i].length()){ length = strs[i].length(); } } int j = 0; while(j<length){ //逐个字符遍历所有字符串 char a = strs[0].charAt(j); for(int i = 1;i<strs.length;i++){ if(a != strs[i].charAt(j)){ flag = false; //若从某个字符不相等,跳出循环 break; } } if(flag == false){ break; } result = result+a; //若都相等,则最终字符串加上相等字符 j++; } return result; } }
相关文章推荐
- 仿京东数据库表单的sql设计
- MOOC北京理工《C语言程序设计(上)》第6周第1题:数字正方形
- socket tcp/ip
- 已拦截跨源请求:同源策略禁止读取位于 http://localhost:8080/*的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。
- 使用tftpd32烧写内核(拯救你的“砖”)
- 开展软件測試工作的前期準備
- [Effective JavaScript笔记]第1条:了解使用的js版本
- 《领域驱动设计的原则与实践》读书笔记(一)
- 检测当前网络是否可用
- C++11 模板元编程初探: 在编译期间确定斐波那契数列
- Android直播,音视频播放那些事儿
- Android Data Binding
- [置顶] 关于Idea基于maven创建springMvc项目中配置文件自动扫描找不到base-package问题
- 用My97扩展ExtJs日期时间插件 (EXT不支持时分秒,我们借助my97完成需求)
- windows下vc进行内存泄露终结版
- MYSQL之union和order by分析([Err] 1221 - Incorrect usage of UNION and ORDER BY)
- UICollectionViewFlowLayout使用示例
- Guava并发:ListenableFuture与RateLimiter示例
- ProGuard详解
- Android AutoLayout全新的适配方式 堪称适配终结者