File tree 2 files changed +55
-0
lines changed
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 8
8
- [ Two Sum] ( https://github.com/ScoutYin/LeetCode-JavaScript/blob/master/solutions/easy/twoSum.md )
9
9
- [ Search Insert Position] ( https://github.com/ScoutYin/LeetCode-JavaScript/blob/master/solutions/easy/searchInsert.md )
10
10
- [ Count And Say] ( https://github.com/ScoutYin/LeetCode-Javascript/blob/master/solutions/easy/countAndSay.md )
11
+ - [ 最长公共前缀] ( https://github.com/ScoutYin/LeetCode-Javascript/blob/master/solutions/easy/longestCommonPrefix.md )
11
12
12
13
### Medium
13
14
Original file line number Diff line number Diff line change
1
+ ## 最长公共前缀
2
+
3
+ > [ 领扣-最长公共前缀] ( https://leetcode-cn.com/problems/longest-common-prefix/description/ )
4
+
5
+ ### Question
6
+
7
+ 编写一个函数来查找字符串数组中的最长公共前缀。
8
+
9
+ 如果不存在公共前缀,返回空字符串 ""。
10
+
11
+ 所有输入只包含小写字母 a-z 。
12
+
13
+ #### Example:
14
+ ``` shell
15
+ 输入:[" flower" ," flow" ," flight" ]
16
+ 输出:" fl"
17
+ ```
18
+
19
+ ``` shell
20
+ 输入: [" dog" ," racecar" ," car" ]
21
+ 输出: " "
22
+ 解释: 输入不存在公共前缀。
23
+ ```
24
+
25
+ ### Solution
26
+ ``` javascript
27
+ /**
28
+ * @param {string[]} strs
29
+ * @return {string}
30
+ */
31
+ const longestCommonPrefix = (strs ) => {
32
+ if (! strs .length || strs[0 ] === ' ' ) return ' '
33
+ if (strs .length === 1 ) return strs[0 ]
34
+ let index = 1
35
+ let last = ' '
36
+ let prefix = ' '
37
+ const check = () => {
38
+ prefix = strs[0 ].substring (0 , index)
39
+ if (last === prefix) return
40
+ const isCommon = strs .every (str => str .indexOf (prefix) === 0 )
41
+ if (isCommon) {
42
+ last = prefix
43
+ index++
44
+ check ()
45
+ }
46
+ }
47
+ check ()
48
+ return last
49
+ }
50
+ ```
51
+
52
+ ### 需注意的的几种情况
53
+
54
+ 输入:` [] ` 、` [""] ` 、` ["a"] ` 、` ["a", "a"] `
You can’t perform that action at this time.
0 commit comments