面试经典-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;
    }
}
相关推荐
qq_459340392 小时前
大厂面试题备份20250201
面试
皮卡丘のcoding12 小时前
蓝桥杯备赛练习题01
职场和发展·蓝桥杯
不过四级不改名67713 小时前
蓝桥杯嵌入式uart,iic,adc_scan模版
职场和发展·蓝桥杯
Joyner201814 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
LNsupermali14 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展
雾月5514 小时前
LeetCode LCR180文件组合
算法·leetcode·职场和发展
Dr.勿忘15 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
labmem117 小时前
Leetcode:541
算法·leetcode·职场和发展
今天也想MK代码20 小时前
写好简历的三个关键认知
面试·职场和发展
好记性+烂笔头1 天前
4 Hadoop 面试真题
大数据·hadoop·面试