Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- pandas
- crawler
- Classes
- strings
- Linux
- noob
- Anime
- GIT
- project
- ansible
- API
- JSON
- python
- commands
- .gitignore
- MyAnimeList
- Blockchain
- DATABASE
- forks
- directories
- github
- Filecoin
- cached
- SCV
- basics
- MySQL
- Jupyter Notebook
- Methods
- workbench
- Django
Archives
- Today
- Total
제니 블로그
Solving Leetcode : Longest common prefix 본문
This is leetcode problem number 14, difficulty of "Easy".
Problem being :
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return ""
The leetcode provides us with the starting :
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
the longestCommonPrefix function will need list as an argument.
The way I thought of first, is using enumerate to loop through all the letters in the list.
prefix = strs[0]
for count, value in enumerate(strs[1:], 1):
while value.find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
if not strs:
return ""
- Function initializes the
prefixvariable to the first string in the list, thus it being set to strs[0]. - Iterates over the remaining strings in
strsusingenumeratewith a starting index of 1 -->counttakes on values 1, 2, 3, etc... - Enter a
whileloop that checks whether theprefixis a valid prefix ofs - Use a
.find()method of string, returning the index of the first occurence of the substringprefixins. - If there is no prefix, return nothing.
The runtime ended up with 37ms, beating 56.29% of the other solutions summited, and 13.9 MB of memory taken, beating 79.57%.
'Building Blocks' 카테고리의 다른 글
| Using Ansible (0) | 2025.05.12 |
|---|---|
| Installing Ansible (0) | 2025.05.12 |
| Using .gitignore (0) | 2023.03.09 |
| Linux - Simple Commands and Navigation Part 1 (0) | 2023.02.17 |
| Basics of Github - Concepts (0) | 2023.02.16 |