File tree Expand file tree Collapse file tree 2 files changed +85
-0
lines changed
Expand file tree Collapse file tree 2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change 1+ <h1 style =" text-align : center ;" > <span style =" color : #00AF9B ;" >14. 最长公共前缀</span > </h1 >
2+
3+ ### 🚀 LeetCode
4+
5+ <base target =" _blank " >
6+
7+ <span style =" color : #00AF9B ;" >** Easy** </span > [ ** https://leetcode.cn/problems/longest-common-prefix/ ** ] ( https://leetcode.cn/problems/longest-common-prefix/ )
8+
9+ ---
10+
11+ ### ❓ Description
12+
13+ <br />
14+
15+ 编写一个函数来查找字符串数组中的最长公共前缀。
16+
17+ 如果不存在公共前缀,返回空字符串 ` "" ` 。
18+
19+ <br />
20+
21+ ** 示例 1:**
22+
23+ ```
24+ 输入: strs = ["flower", "flow", "flight"]
25+ 输出: "fl"
26+ ```
27+
28+ ** 示例 2:**
29+
30+ ```
31+ 输入: strs = ["dog", "racecar", "car"]
32+ 输出: ""
33+ 解释: 输入不存在公共前缀
34+ ```
35+
36+ <br />
37+
38+ ** 提示:**
39+
40+ * ` 1 <= strs.length <= 200 `
41+ * ` 0 <= strs[i].length <= 200 `
42+ * ` strs[i] ` 仅由小写英文字母组成
43+
44+ ---
45+
46+ ### ❗ Solution
47+
48+ <br />
49+
50+ #### Java
51+
52+ ```
53+ class Solution {
54+ public String longestCommonPrefix(String[] strs) {
55+ if (strs.length == 1) {
56+ return strs[0];
57+ }
58+
59+ int length = Integer.MAX_VALUE;
60+ for (String str : strs) {
61+ length = Math.min(length, str.length());
62+ }
63+
64+ StringBuilder result = new StringBuilder();
65+ boolean end = false;
66+
67+ for (int i = 0; i < length; i++) {
68+ Character c = strs[0].charAt(i);
69+ for (int j = 1; j < strs.length; j++) {
70+ if (!c.equals(strs[j].charAt(i))) {
71+ end = true;
72+ break;
73+ }
74+ }
75+ if (end) {
76+ break;
77+ } else {
78+ result.append(c);
79+ }
80+ }
81+ return result.toString();
82+ }
83+ }
84+ ```
Original file line number Diff line number Diff line change 1212| <span style =" color : #FFB822 ;" >** Medium** </span > | [ ** 0011.盛最多水的容器** ] ( ../medium/0011.盛最多水的容器.md ) |
1313| <span style =" color : #FFB822 ;" >** Medium** </span > | [ ** 0012.整数转罗马数字** ] ( ../medium/0012.整数转罗马数字.md ) |
1414| <span style =" color : #00AF9B ;" >** Easy** </span > | [ ** 0013.罗马数字转整数** ] ( ../easy/0013.罗马数字转整数.md ) |
15+ | <span style =" color : #00AF9B ;" >** Easy** </span > | [ ** 0014.最长公共前缀** ] ( ../easy/0014.最长公共前缀.md ) |
1516| <span style =" color : #FFB822 ;" >** Medium** </span > | [ ** 0015.三数之和** ] ( ../medium/0015.三数之和.md ) |
1617| <span style =" color : #FFB822 ;" >** Medium** </span > | [ ** 0016.最接近的三数之和** ] ( ../medium/0016.最接近的三数之和.md ) |
1718| <span style =" color : #00AF9B ;" >** Easy** </span > | [ ** 0020.有效的括号** ] ( ../easy/0020.有效的括号.md ) |
You can’t perform that action at this time.
0 commit comments