#力扣: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]
			}
		}
	}
}
相关推荐
AI科技星4 小时前
从ZUFT光速螺旋运动求导推出自然常数e
服务器·人工智能·线性代数·算法·矩阵
老鼠只爱大米4 小时前
LeetCode经典算法面试题 #78:子集(回溯法、迭代法、动态规划等多种实现方案详细解析)
算法·leetcode·动态规划·回溯·位运算·子集
执着2594 小时前
力扣hot100 - 199、二叉树的右视图
数据结构·算法·leetcode
I_LPL4 小时前
day21 代码随想录算法训练营 二叉树专题8
算法·二叉树·递归
可编程芯片开发5 小时前
基于PSO粒子群优化PI控制器的无刷直流电机最优控制系统simulink建模与仿真
人工智能·算法·simulink·pso·pi控制器·pso-pi
cpp_25015 小时前
P8448 [LSOT-1] 暴龙的土豆
数据结构·c++·算法·题解·洛谷
YGGP5 小时前
【Golang】LeetCode 49. 字母异位词分组
leetcode
lcj25115 小时前
深入理解指针(4):qsort 函数 & 通过冒泡排序实现
c语言·数据结构·算法
fie88895 小时前
基于MATLAB的转子动力学建模与仿真实现(含碰摩、不平衡激励)
开发语言·算法·matlab
唐梓航-求职中5 小时前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode