索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
014.Longest_Common_Prefix (Easy)
链接:
题目:https://oj.leetcode.com/problems/longest-common-prefix/
代码(github):https://github.com/illuz/leetcode
题意:
求多个字符串的最长公共前缀。
分析:
一位一位判断即可,没什么坑点。
代码:
C++:
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.empty()) return ""; for (int i = 0; i < strs[0].length(); i++) { for (int j = 1; j < strs.size(); j++) if (i >= strs[j].length() || strs[j][i] != strs[0][i]) return strs[0].substr(0, i); } return strs[0]; } };
Java:
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; for (int i = 0; i < strs[0].length(); i++) { for (int j = 1; j < strs.length; j++) if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) return strs[0].substring(0, i); } return strs[0]; } }
Python:
class Solution: # @return a string def longestCommonPrefix(self, strs): if strs == []: return '' for i in range(len(strs[0])): for str in strs: if len(str) <= i or str[i] != strs[0][i]: return strs[0][:i] return strs[0]
时间: 2024-11-15 01:02:29