Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit acd9a4a

Browse files
committed
Longest common prefix problem
1 parent 045d3fc commit acd9a4a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎README.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,3 +217,48 @@ var romanToInt = (s) => {
217217
return result;
218218
};
219219
```
220+
221+
## Longest Common Prefix
222+
223+
Write a function to find the longest common prefix string amongst an array of strings.
224+
225+
If there is no common prefix, return an empty string "".
226+
227+
**Example 1**:
228+
229+
```js
230+
Input: strs = ["flower", "flow", "flight"];
231+
Output: "fl";
232+
```
233+
234+
**Example 2**:
235+
236+
```js
237+
Input: strs = ["dog","racecar","car"]
238+
Output: ""
239+
Explanation: There is no common prefix among the input strings.
240+
```
241+
242+
**Constraints**:
243+
244+
- 1 <= strs.length <= 200
245+
- 0 <= strs[i].length <= 200
246+
- strs[i] consists of only lowercase English letters.
247+
248+
## **Solution**
249+
250+
```js
251+
var longestCommonPrefix = function (strs) {
252+
if (!strs.length) return "";
253+
254+
for (let i = 0; i < strs[0].length; i++) {
255+
for (let j = 1; j < strs.length; j++) {
256+
if (strs[0][i] !== strs[j][i]) {
257+
return strs[0].slice(0, i);
258+
}
259+
}
260+
}
261+
262+
return strs[0];
263+
};
264+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /