面试经典-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;
    }
}
相关推荐
skywalker_111 天前
力扣hot100-7(接雨水),8(无重复字符的最长子串)
算法·leetcode·职场和发展
田梓燊1 天前
leetcode 160
算法·leetcode·职场和发展
Moment1 天前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试
Moment1 天前
AI全栈入门指南:NestJs 中的 DTO 和数据校验
前端·后端·面试
Moment1 天前
当前端开始做 Agent 后,我才知道 LangGraph 有多重要❗❗❗
前端·后端·面试
Ruihong1 天前
你的 Vue 3 reactive(),VuReact 会编译成什么样的 React?
vue.js·面试
Ruihong1 天前
你的 Vue 3 ref(),VuReact 会编译成什么样的 React?
vue.js·面试
yuki_uix1 天前
跨域与安全:CORS、HTTPS 与浏览器安全机制
前端·面试
_深海凉_1 天前
LeetCode热题100-找到字符串中所有字母异位词
算法·leetcode·职场和发展