|
| 1 | +# Problem: Longest Common Prefix |
| 2 | +# Link: https://leetcode.com/problems/longest-common-prefix/description/ |
| 3 | +# Tags: String |
| 4 | +# Approach: Take the first word as a template and compare each character index |
| 5 | +# against all other words; stop at the first mismatch or length overrun. |
| 6 | +# Time Complexity: O(S) where S is the sum of all characters |
| 7 | +# Space Complexity: O(1) |
| 8 | + |
| 9 | + |
| 10 | +class Solution: |
| 11 | + def longestCommonPrefix(self, strs): |
| 12 | + if not strs: |
| 13 | + return "" |
| 14 | + first = strs[0] |
| 15 | + for i in range(len(first)): |
| 16 | + ch = first[i] |
| 17 | + for w in strs[1:]: |
| 18 | + if i == len(w) or w[i] != ch: |
| 19 | + return first[:i] |
| 20 | + return first |
0 commit comments