鱼C论坛

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

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

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

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

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

x
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 "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

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

All given inputs are in lowercase letters a-z.

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        if(strs == null || strs.length == 0) return "";
        
        if(strs.length == 1) return strs[0];
        
        int len = strs.length;
        
        int index = 0;
        
        String result = "";
        
        while(true){
            
        int count = 1;
        
        for(int i = 1; i< len; i++){
            
            if(strs[i-1].length() == 0 || strs[i].length() == 0) return "";
            
            if(index +1 > strs[i-1].length() || index +1 > strs[i].length()) return result;

            
            if(strs[i-1].charAt(index) == (strs[i].charAt(index) )){
                
                count++;
            }
            
            else{
                
                return result;
            }
            
            if(count == len){
                
                result = result + strs[i].charAt(index) ;
                
                index++;
                
            }
        }
            
        }
        
    }
}
class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        if(strs == null || strs.length == 0) return "";
        
        String cur = strs[0];
        
        int len = strs.length;
        
        for(int i = 1; i< len; i++){
            
            while(strs[i].indexOf(cur) != 0){
                
                cur = cur.substring(0, cur.length() -1);
                
            }
        }
        
        return cur;
        
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-27 06:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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