美文网首页LeetCode每日一题
LeetCode每日一题:最长公共前缀

LeetCode每日一题:最长公共前缀

作者: Patarw | 来源:发表于2020-08-09 21:17 被阅读0次

第一种思路:两个字符串相比较,把共有的部分作为一个字符串再和下一个相比较,直到遍历完所有数组得到结果

  • 代码实现:
class Solution {
public String longestCommonPrefix(String[] strs) {   
    if(strs.length == 0){
        return "";
    }         
    String temp = strs[0];
    for(int i = 1;i < strs.length;i++){              
        int index = 0;           
        int len1 = temp.length();
        int len2 = strs[i].length();
        while(index < len1 && index < len2){
            if(temp.charAt(index) != strs[i].charAt(index)){
                break;              
            }  
            index++;     
        }
        temp = temp.substring(0,index);
    }
    return temp;
}
}

第二种思路就是从数组中所有元素中的第一个元素开始比较,直到出现不同字符的时候才返回,这个我就不写代码了,还挺简单的

相关文章

网友评论

    本文标题:LeetCode每日一题:最长公共前缀

    本文链接:https://www.haomeiwen.com/subject/sidrdktx.html