面试经典-22-最长公共前缀

题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入:strs = ["flower","flow","flight"]

输出:"fl"

java 复制代码
class Solution {
    public String longestCommonPrefix(String[] strs) {
        String result = strs[0];
        for(int i = 1;i< strs.length;i++){
            StringBuffer res = new StringBuffer();
            for(int j = 0;j< result.length() && j< strs[i].length();j++){
                if(result.charAt(j) == strs[i].charAt(j)){
                    res.append(result.charAt(j));
                }else{
                    break;
                }
            }
            result = res.toString();
        }
        return result;
    }
}
相关推荐
Chan1614 分钟前
Java 集合面试核心:ArrayList/LinkedList 底层数据结构,HashMap扩容机制详解
java·数据结构·spring boot·面试·intellij-idea
Swift社区1 小时前
LeetCode 425 - 单词方块
算法·leetcode·职场和发展
yunxi_053 小时前
分布式文件服务实战稿:从本地存储到对象存储的架构升级
后端·面试
Chan163 小时前
【 Java八股文面试 | Redis篇 缓存问题、持久化、分布式锁 】
java·数据库·redis·后端·spring·缓存·面试
zhishidi5 小时前
大模型个性化推荐面试指南
人工智能·面试
程序员小远6 小时前
软件测试之bug分析定位技巧
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·bug
Kuo-Teng6 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng6 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
元亓亓亓8 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
橘颂TA8 小时前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法