49
49
``` python
50
50
class Solution :
51
51
def longestCommonPrefix (self , strs : List[str ]) -> str :
52
- n = len (strs)
53
- if n == 0 :
54
- return ' '
52
+ for l in range (len (strs[0 ]), - 1 , - 1 ):
53
+ if all (len (s) >= l and s[:l] == strs[0 ][:l] for s in strs):
54
+ return strs[0 ][:l]
55
+ return ' '
56
+ ```
57
+
58
+ ``` python
59
+ class Solution :
60
+ def longestCommonPrefix (self , strs : List[str ]) -> str :
55
61
for i in range (len (strs[0 ])):
56
- for j in range ( 1 , n) :
57
- if len (strs[j] ) <= i or strs[j] [i] != strs[0 ][i]:
58
- return strs[ 0 ] [:i]
62
+ for s in strs[ 1 :] :
63
+ if len (s ) <= i or s [i] != strs[0 ][i]:
64
+ return s [:i]
59
65
return strs[0 ]
60
66
```
61
67
@@ -66,8 +72,7 @@ class Solution:
66
72
``` java
67
73
class Solution {
68
74
public String longestCommonPrefix (String [] strs ) {
69
- int n;
70
- if ((n = strs. length) == 0 ) return " " ;
75
+ int n = strs. length;
71
76
for (int i = 0 ; i < strs[0 ]. length(); ++ i) {
72
77
for (int j = 1 ; j < n; ++ j) {
73
78
if (strs[j]. length() <= i || strs[j]. charAt(i) != strs[0 ]. charAt(i)) {
@@ -86,8 +91,7 @@ class Solution {
86
91
class Solution {
87
92
public:
88
93
string longestCommonPrefix(vector<string >& strs) {
89
- int n;
90
- if ((n = strs.size()) == 0) return "";
94
+ int n = strs.size();
91
95
for (int i = 0; i < strs[ 0] .size(); ++i) {
92
96
for (int j = 1; j < n; ++j) {
93
97
if (strs[ j] .size() <= i || strs[ j] [ i ] != strs[ 0] [ i ] ) {
@@ -104,24 +108,15 @@ public:
104
108
105
109
```go
106
110
func longestCommonPrefix(strs []string) string {
107
- if len(strs) == 0 {
108
- return ""
109
- }
110
-
111
- var b strings.Builder
112
- m, n := len(strs[0]), len(strs)
113
-
114
- LOOP:
115
- for i := 0; i < m; i++ {
111
+ n := len(strs)
112
+ for i := range strs[0] {
116
113
for j := 1; j < n; j++ {
117
- if i >= len(strs[j]) || strs[0 ][i] != strs[j ][i] {
118
- break LOOP
114
+ if len(strs[j]) <= i || strs[j ][i] != strs[0 ][i] {
115
+ return strs[0][:i]
119
116
}
120
117
}
121
- b.WriteByte(strs[0][i])
122
118
}
123
-
124
- return b.String()
119
+ return strs[0]
125
120
}
126
121
```
127
122
185
180
### ** JavaScript**
186
181
187
182
``` js
188
- const longestCommonPrefix = function (strs ) {
189
- if (strs .length === 0 ) return ' ' ;
183
+ /**
184
+ * @param {string[]} strs
185
+ * @return {string}
186
+ */
187
+ var longestCommonPrefix = function (strs ) {
190
188
for (let j = 0 ; j < strs[0 ].length ; j++ ) {
191
189
for (let i = 0 ; i < strs .length ; i++ ) {
192
190
if (strs[0 ][j] !== strs[i][j]) {
0 commit comments