#力扣:14. 最长公共前缀@FDDLC

14. 最长公共前缀

一、Java

java 复制代码
class Solution {
    public String longestCommonPrefix(String[] strs) {
        for (int l = 0; ; l++) {
            for (int i = 0; i < strs.length; i++) {
                if (l >= strs[i].length() || strs[i].charAt(l) != strs[0].charAt(l)) return strs[0].substring(0, l);
            }
        }
    }
}

二、C++

cpp 复制代码
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        for (int l = 0;; l++) {
            for (int i = 0; i < strs.size(); i++) {
                if (l >= strs[i].length() || strs[i][l] != strs[0][l]) return strs[0].substr(0, l);
            }
        }
    }
};

三、Python

python 复制代码
from typing import List


class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        l = 0
        while True:
            for i in range(len(strs)):
                if l >= len(strs[i]) or strs[i][l] != strs[0][l]:
                    return strs[0][0:l]
            l += 1

四、JavaScript

javascript 复制代码
var longestCommonPrefix = function (strs) {
    for (let l = 0; ; l++) {
        for (let i = 0; i < strs.length; i++) {
            if (l >= strs[i].length || strs[i][l] != strs[0][l]) return strs[0].substring(0, l);
        }
    }
};

五、Go

Go 复制代码
package main

func longestCommonPrefix(strs []string) string {
	for l := 0; ; l++ {
		for i := 0; i < len(strs); i++ {
			if l >= len(strs[i]) || strs[i][l] != strs[0][l] {
				return strs[0][0:l]
			}
		}
	}
}
相关推荐
深邃-7 小时前
【数据结构与算法】-二叉树(2):实现顺序结构二叉树(堆的实现),向上调整算法,向下调整算法,堆排序,TOP-K问题
数据结构·算法·二叉树·排序算法·堆排序··top-k
We་ct10 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程14 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮15 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说15 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove16 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
小程故事多_8016 小时前
[大模型面试系列] 多轮对话 Agent 设计实战(含窗口优化 + 工具调用精髓)
人工智能·面试·职场和发展
leoufung16 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了16 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL16 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化