鱼C论坛

 找回密码
 立即注册
查看: 2284|回复: 0

[学习笔记] leetcode 14. Longest Common Prefix

[复制链接]
发表于 2019-8-30 00:11:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  2. If there is no common prefix, return an empty string "".

  3. Example 1:

  4. Input: ["flower","flow","flight"]
  5. Output: "fl"
  6. Example 2:

  7. Input: ["dog","racecar","car"]
  8. Output: ""
  9. Explanation: There is no common prefix among the input strings.
  10. Note:

  11. All given inputs are in lowercase letters a-z.
复制代码


  1. class Solution {
  2.     public String longestCommonPrefix(String[] strs) {
  3.         
  4.         if(strs == null || strs.length == 0) return "";
  5.         
  6.         if(strs.length == 1) return strs[0];
  7.         
  8.         int len = strs.length;
  9.         
  10.         int index = 0;
  11.         
  12.         String result = "";
  13.         
  14.         while(true){
  15.             
  16.         int count = 1;
  17.         
  18.         for(int i = 1; i< len; i++){
  19.             
  20.             if(strs[i-1].length() == 0 || strs[i].length() == 0) return "";
  21.             
  22.             if(index +1 > strs[i-1].length() || index +1 > strs[i].length()) return result;

  23.             
  24.             if(strs[i-1].charAt(index) == (strs[i].charAt(index) )){
  25.                
  26.                 count++;
  27.             }
  28.             
  29.             else{
  30.                
  31.                 return result;
  32.             }
  33.             
  34.             if(count == len){
  35.                
  36.                 result = result + strs[i].charAt(index) ;
  37.                
  38.                 index++;
  39.                
  40.             }
  41.         }
  42.             
  43.         }
  44.         
  45.     }
  46. }
复制代码

  1. class Solution {
  2.     public String longestCommonPrefix(String[] strs) {
  3.         
  4.         if(strs == null || strs.length == 0) return "";
  5.         
  6.         String cur = strs[0];
  7.         
  8.         int len = strs.length;
  9.         
  10.         for(int i = 1; i< len; i++){
  11.             
  12.             while(strs[i].indexOf(cur) != 0){
  13.                
  14.                 cur = cur.substring(0, cur.length() -1);
  15.                
  16.             }
  17.         }
  18.         
  19.         return cur;
  20.         
  21.     }
  22. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 17:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表